blob: 99042afa3a1bae17bdbc9919645559c998924d7b [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,
1754 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1755 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1756 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1757 // preferred).
1758 std::vector<audio_channel_mask_t> masks = {{
1759 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1760 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1761 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1762 // insert index masks (higher counts most preferred) as preferred over position masks
1763 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1764 masks.insert(
1765 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1766 }
1767 return masks;
1768 }();
1769
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001770 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001771 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1772 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001773 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001774 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1775 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001776 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001777 }
1778 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1779 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1780 sinkConfig->format = bestSinkConfig.format;
1781 // For encoded streams force direct flag to prevent downstream mixing.
1782 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1783 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001784 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1785 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001786 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001787 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1788 // raw and IEC61937 framed streams.
1789 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1790 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1791 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001792 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1793 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001794 sourceConfig->channel_mask =
1795 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1796 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1797 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001798 sourceConfig->format = bestSinkConfig.format;
1799 // Copy input stream directly without any processing (e.g. resampling).
1800 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1801 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1802 if (hwAvSync) {
1803 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1804 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1805 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1806 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1807 }
1808 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1809 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1810 sinkConfig->config_mask |= config_mask;
1811 sourceConfig->config_mask |= config_mask;
1812 return NO_ERROR;
1813}
1814
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001815PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1816 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001817{
1818 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001819 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1820 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1821 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1822 if (deviceModule == nullptr) {
1823 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1824 return patchBuilder;
1825 }
1826 const InputProfileCollection inputProfiles = msdIsSource ?
1827 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1828 const OutputProfileCollection outputProfiles = msdIsSource ?
1829 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1830
1831 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1832 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1833 device : getMsdAudioOutDevices().itemAt(0);
1834 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1835
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001836 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1837 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001838 AudioProfileVector sourceProfiles;
1839 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001840 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1841 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001842 for (auto hwAvSync : { true, false }) {
1843 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1844 sourceProfiles, sinkProfiles) != NO_ERROR) {
1845 continue;
1846 }
1847 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1848 &sinkConfig) == NO_ERROR) {
1849 // Found a matching config. Re-create PatchBuilder with this config.
1850 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1851 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001852 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001853 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001854 " supporting PCM format conversion.", __func__);
1855 return patchBuilder;
1856}
1857
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001858status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001859 DeviceVector devices;
1860 if (outputDevices != nullptr && outputDevices->size() > 0) {
1861 devices.add(*outputDevices);
1862 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001863 // Use media strategy for unspecified output device. This should only
1864 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1865 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001866 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001867 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001868 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001869 }
Michael Chan6fb34492020-12-08 15:44:49 +11001870 std::vector<PatchBuilder> patchesToCreate;
1871 for (auto i = 0u; i < devices.size(); ++i) {
1872 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001873 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001874 }
1875 // Retain only the MSD patches associated with outputDevices request.
1876 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001877 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001878 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1879 auto retainedPatch = false;
1880 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1881 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1882 patchesToRemove.removeItemsAt(i);
1883 retainedPatch = true;
1884 break;
1885 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001886 }
Michael Chan6fb34492020-12-08 15:44:49 +11001887 if (retainedPatch) {
1888 it = patchesToCreate.erase(it);
1889 continue;
1890 }
1891 ++it;
1892 }
1893 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1894 return NO_ERROR;
1895 }
1896 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1897 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001898 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001899 }
Michael Chan6fb34492020-12-08 15:44:49 +11001900 status_t status = NO_ERROR;
1901 for (const auto &p : patchesToCreate) {
1902 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1903 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1904 char message[256];
1905 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1906 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1907 currStatus == NO_ERROR ? "Success" : "Error",
1908 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1909 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1910 if (currStatus == NO_ERROR) {
1911 ALOGD("%s", message);
1912 } else {
1913 ALOGE("%s", message);
1914 if (status == NO_ERROR) {
1915 status = currStatus;
1916 }
1917 }
1918 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001919 return status;
1920}
1921
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001922void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1923 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001924 for (size_t i = 0; i < msdPatches.size(); i++) {
1925 const auto& patch = msdPatches[i];
1926 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1927 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1928 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1929 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1930 releaseAudioPatch(patch->getHandle(), mUidCached);
1931 break;
1932 }
1933 }
1934 }
1935}
1936
Dorin Drimus94d94412022-02-02 09:05:02 +01001937bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001938 DeviceVector devicesToCheck =
1939 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001940 AudioPatchCollection msdPatches = getMsdOutputPatches();
1941 for (size_t i = 0; i < msdPatches.size(); i++) {
1942 const auto& patch = msdPatches[i];
1943 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1944 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1945 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1946 const auto& foundDevice = devicesToCheck.getDevice(
1947 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1948 if (foundDevice != nullptr) {
1949 devicesToCheck.remove(foundDevice);
1950 if (devicesToCheck.isEmpty()) {
1951 return true;
1952 }
1953 }
1954 }
1955 }
1956 }
1957 return false;
1958}
1959
Eric Laurente0720872014-03-11 09:30:41 -07001960audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001961 audio_output_flags_t flags,
1962 audio_format_t format,
1963 audio_channel_mask_t channelMask,
1964 uint32_t samplingRate,
1965 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001966{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001967 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1968 "%s called with format %#x", __func__, format);
1969
jiabinebb6af42020-06-09 17:31:17 -07001970 // Return the output that haptic-generating attached to when 1) session id is specified,
1971 // 2) haptic-generating effect exists for given session id and 3) the output that
1972 // haptic-generating effect attached to is in given outputs.
1973 if (sessionId != AUDIO_SESSION_NONE) {
1974 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1975 sessionId, FX_IID_HAPTICGENERATOR);
1976 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1977 return hapticGeneratingOutput;
1978 }
1979 }
1980
Eric Laurent16c66dd2019-05-01 17:54:10 -07001981 // Flags disqualifying an output: the match must happen before calling selectOutput()
1982 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1983 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1984
1985 // Flags expressing a functional request: must be honored in priority over
1986 // other criteria
1987 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1988 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001989 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1990 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001991 // Flags expressing a performance request: have lower priority than serving
1992 // requested sampling rate or channel mask
1993 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1994 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1995 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1996
1997 const audio_output_flags_t functionalFlags =
1998 (audio_output_flags_t)(flags & kFunctionalFlags);
1999 const audio_output_flags_t performanceFlags =
2000 (audio_output_flags_t)(flags & kPerformanceFlags);
2001
2002 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2003
Eric Laurente552edb2014-03-10 17:42:56 -07002004 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002005 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002006 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002007 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002008 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002009 // with tiebreak preferring the minimum number of extra functional flags
2010 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002011 // 3: the output supporting the exact channel mask
2012 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002013 // 5: the output with the highest sampling rate if the requested sample rate is
2014 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002015 // 6: the output with the highest number of requested performance flags
2016 // 7: the output with the bit depth the closest to the requested one
2017 // 8: the primary output
2018 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002019
Eric Laurent16c66dd2019-05-01 17:54:10 -07002020 // matching criteria values in priority order for best matching output so far
2021 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002022
Eric Laurent16c66dd2019-05-01 17:54:10 -07002023 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2024 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2025 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002026
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002027 for (audio_io_handle_t output : outputs) {
2028 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002029 // matching criteria values in priority order for current output
2030 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002031
Eric Laurent16c66dd2019-05-01 17:54:10 -07002032 if (outputDesc->isDuplicated()) {
2033 continue;
2034 }
2035 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2036 continue;
2037 }
Eric Laurent8838a382014-09-08 16:44:28 -07002038
Eric Laurent16c66dd2019-05-01 17:54:10 -07002039 // If haptic channel is specified, use the haptic output if present.
2040 // When using haptic output, same audio format and sample rate are required.
2041 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002042 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002043 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2044 continue;
2045 }
2046 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002047 && format == outputDesc->getFormat()
2048 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002049 currentMatchCriteria[0] = outputHapticChannelCount;
2050 }
2051
2052 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002053 const int matchingFunctionalFlags =
2054 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2055 const int totalFunctionalFlags =
2056 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2057 // Prefer matching functional flags, but subtract unnecessary functional flags.
2058 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002059
2060 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002061 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2062 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002063 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2064 channelCount <= outputChannelCount) {
2065 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002066 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2067 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002068 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002069 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002070 currentMatchCriteria[3] = outputChannelCount;
2071 }
2072
2073 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002074 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002075 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002076 }
2077
2078 // performance flags match
2079 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2080
2081 // format match
2082 if (format != AUDIO_FORMAT_INVALID) {
2083 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002084 PolicyAudioPort::kFormatDistanceMax -
2085 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002086 }
2087
2088 // primary output match
2089 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2090
2091 // compare match criteria by priority then value
2092 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2093 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2094 bestMatchCriteria = currentMatchCriteria;
2095 bestOutput = output;
2096
2097 std::stringstream result;
2098 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2099 std::ostream_iterator<int>(result, " "));
2100 ALOGV("%s new bestOutput %d criteria %s",
2101 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002102 }
2103 }
2104
Eric Laurent16c66dd2019-05-01 17:54:10 -07002105 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002106}
2107
Eric Laurent8fc147b2018-07-22 19:13:55 -07002108status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002109{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002110 ALOGV("%s portId %d", __FUNCTION__, portId);
2111
2112 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2113 if (outputDesc == 0) {
2114 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002115 return BAD_VALUE;
2116 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002117 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002118
Eric Laurent8fc147b2018-07-22 19:13:55 -07002119 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002120 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002121
Eric Laurent733ce942017-12-07 12:18:25 -08002122 status_t status = outputDesc->start();
2123 if (status != NO_ERROR) {
2124 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002125 }
2126
Eric Laurent97ac8712018-07-27 18:59:02 -07002127 uint32_t delayMs;
2128 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002129
2130 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002131 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002132 if (status == DEAD_OBJECT) {
2133 sp<SwAudioOutputDescriptor> desc =
2134 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2135 if (desc == nullptr) {
2136 // This is not common, it may indicate something wrong with the HAL.
2137 ALOGE("%s unable to open output with default config", __func__);
2138 return status;
2139 }
2140 desc->mUsePreferredMixerAttributes = true;
2141 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002142 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002143 }
jiabina84c3d32022-12-02 18:59:55 +00002144
2145 // If the client is the first one active on preferred mixer parameters, reopen the output
2146 // if the current mixer parameters doesn't match the preferred one.
2147 if (outputDesc->devices().size() == 1) {
2148 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2149 outputDesc->devices()[0]->getId(), client->strategy());
2150 if (info != nullptr && info->getUid() == client->uid()) {
2151 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2152 info->getConfigBase(), info->getFlags())) {
2153 stopSource(outputDesc, client);
2154 outputDesc->stop();
2155 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2156 config.channel_mask = info->getConfigBase().channel_mask;
2157 config.sample_rate = info->getConfigBase().sample_rate;
2158 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002159 sp<SwAudioOutputDescriptor> desc =
2160 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2161 if (desc == nullptr) {
2162 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002163 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002164 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002165 // Intentionally return error to let the client side resending request for
2166 // creating and starting.
2167 return DEAD_OBJECT;
2168 }
2169 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002170 if (info->getActiveClientCount() == 1 &&
2171 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2172 // If it is first bit-perfect client, reroute all clients that will be routed to
2173 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2174 PortHandleVector clientsToInvalidate;
2175 for (size_t i = 0; i < mOutputs.size(); i++) {
2176 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002177 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002178 continue;
2179 }
2180 for (const auto& c : mOutputs[i]->getClientIterable()) {
2181 clientsToInvalidate.push_back(c->portId());
2182 }
2183 }
2184 if (!clientsToInvalidate.empty()) {
2185 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2186 __func__);
2187 mpClientInterface->invalidateTracks(clientsToInvalidate);
2188 }
2189 }
jiabina84c3d32022-12-02 18:59:55 +00002190 }
2191 }
2192
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002193 if (client->hasPreferredDevice()) {
2194 // playback activity with preferred device impacts routing occurred, inform upper layers
2195 mpClientInterface->onRoutingUpdated();
2196 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002197 if (delayMs != 0) {
2198 usleep(delayMs * 1000);
2199 }
2200
2201 return status;
2202}
2203
Eric Laurent96d1dda2022-03-14 17:14:19 +01002204bool AudioPolicyManager::isLeUnicastActive() const {
2205 if (isInCall()) {
2206 return true;
2207 }
2208 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2209}
2210
2211bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2212 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2213 return false;
2214 }
2215 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2216 ALOGV("%s active %d", __func__, active);
2217 return active;
2218}
2219
Eric Laurent97ac8712018-07-27 18:59:02 -07002220status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2221 const sp<TrackClientDescriptor>& client,
2222 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002223{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002224 // cannot start playback of STREAM_TTS if any other output is being used
2225 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002226
2227 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002228 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002229 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002230 auto clientStrategy = client->strategy();
2231 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002232 if (stream == AUDIO_STREAM_TTS) {
2233 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002234 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002235 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002236 return INVALID_OPERATION;
2237 } else {
2238 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2239 }
2240 } else {
2241 // some playback other than beacon starts
2242 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2243 }
2244
Eric Laurent77305a62016-07-25 16:39:22 -07002245 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002246 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002247 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002248
François Gaffie11d30102018-11-02 16:09:09 +01002249 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002250 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002251 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002252 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002253 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002254 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002255 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002256 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002257 } else {
2258 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002259 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002260 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2261 AUDIO_FORMAT_DEFAULT);
2262 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2263 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002264 }
2265
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002266 // requiresMuteCheck is false when we can bypass mute strategy.
2267 // It covers a common case when there is no materially active audio
2268 // and muting would result in unnecessary delay and dropped audio.
2269 const uint32_t outputLatencyMs = outputDesc->latency();
2270 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002271 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002272
Eric Laurente552edb2014-03-10 17:42:56 -07002273 // increment usage count for this stream on the requested output:
2274 // NOTE that the usage count is the same for duplicated output and hardware output which is
2275 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002276 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002277
2278 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002279 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002280 // Preferred device may be exclusive, use only if no other active clients on this output
2281 devices = DeviceVector(
2282 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2283 } else {
2284 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2285 }
François Gaffie11d30102018-11-02 16:09:09 +01002286 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002287 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002288 }
2289 }
Eric Laurente552edb2014-03-10 17:42:56 -07002290
François Gaffiec005e562018-11-06 15:04:49 +01002291 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002292 selectOutputForMusicEffects();
2293 }
2294
François Gaffie1c878552018-11-22 16:53:21 +01002295 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002296 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002297 if (devices.isEmpty()) {
2298 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002299 }
François Gaffiec005e562018-11-06 15:04:49 +01002300 bool shouldWait =
2301 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2302 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2303 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002304 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002305 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002306 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002307 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002308 // An output has a shared device if
2309 // - managed by the same hw module
2310 // - supports the currently selected device
2311 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002312 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002313
Eric Laurent77305a62016-07-25 16:39:22 -07002314 // force a device change if any other output is:
2315 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002316 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002317 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002318 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002319 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002320 // change the device currently selected by the other output.
2321 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002322 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002323 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002324 force = true;
2325 }
2326 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002327 // a notification so that audio focus effect can propagate, or that a mute/unmute
2328 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002329 const uint32_t latencyMs = desc->latency();
2330 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2331
2332 if (shouldWait && isActive && (waitMs < latencyMs)) {
2333 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002334 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002335
2336 // Require mute check if another output is on a shared device
2337 // and currently active to have proper drain and avoid pops.
2338 // Note restoring AudioTracks onto this output needs to invoke
2339 // a volume ramp if there is no mute.
2340 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002341 }
2342 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002343
jiabin3ff8d7d2022-12-13 06:27:44 +00002344 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2345 // If the output is open with preferred mixer attributes, but the routed device is
2346 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2347 // changed.
2348 return DEAD_OBJECT;
2349 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002350 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302351 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2352 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002353
Eric Laurente552edb2014-03-10 17:42:56 -07002354 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002355 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002356 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002357 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002358 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002359 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002360 outputDesc->useHwGain() /*force*/)) {
2361 // request AudioService to reinitialize the volume curves asynchronously
2362 ALOGE("checkAndSetVolume failed, requesting volume range init");
2363 mpClientInterface->onVolumeRangeInitRequest();
2364 };
Eric Laurente552edb2014-03-10 17:42:56 -07002365
2366 // update the outputs if starting an output with a stream that can affect notification
2367 // routing
2368 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002369
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002370 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002371 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002372 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002373 }
Eric Laurentdc462862016-07-19 12:29:53 -07002374
2375 if (waitMs > muteWaitMs) {
2376 *delayMs = waitMs - muteWaitMs;
2377 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002378
2379 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2380 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2381 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2382 // change occurs after the MixerThread starts and causes a stream volume
2383 // glitch.
2384 //
2385 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002386 }
Eric Laurentdc462862016-07-19 12:29:53 -07002387
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002388 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002389 mEngine->getForceUse(
2390 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002391 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002392 }
2393
Eric Laurent97ac8712018-07-27 18:59:02 -07002394 // Automatically enable the remote submix input when output is started on a re routing mix
2395 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002396 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2397 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002398 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2399 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2400 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002401 "remote-submix",
2402 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002403 }
2404
Eric Laurent96d1dda2022-03-14 17:14:19 +01002405 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2406
Eric Laurente552edb2014-03-10 17:42:56 -07002407 return NO_ERROR;
2408}
2409
Eric Laurent96d1dda2022-03-14 17:14:19 +01002410void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2411 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2412 bool isUnicastActive = isLeUnicastActive();
2413
2414 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002415 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002416 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2417 for (size_t i = 0; i < mOutputs.size(); i++) {
2418 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2419 if (desc != ignoredOutput && desc->isActive()
2420 && ((isUnicastActive &&
2421 !desc->devices().
2422 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2423 || (wasUnicastActive &&
2424 !desc->devices().getDevicesFromTypes(
2425 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2426 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2427 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002428 if (desc->mUsePreferredMixerAttributes && force) {
2429 // If the device is using preferred mixer attributes, the output need to reopen
2430 // with default configuration when the new selected devices are different from
2431 // current routing devices.
2432 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2433 continue;
2434 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302435 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002436 // re-apply device specific volume if not done by setOutputDevice()
2437 if (!force) {
2438 applyStreamVolumes(desc, newDevices.types(), delayMs);
2439 }
2440 }
2441 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002442 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002443 }
2444}
2445
Eric Laurent8fc147b2018-07-22 19:13:55 -07002446status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002447{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002448 ALOGV("%s portId %d", __FUNCTION__, portId);
2449
2450 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2451 if (outputDesc == 0) {
2452 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002453 return BAD_VALUE;
2454 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002455 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002456
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002457 if (client->hasPreferredDevice(true)) {
2458 // playback activity with preferred device impacts routing occurred, inform upper layers
2459 mpClientInterface->onRoutingUpdated();
2460 }
2461
Eric Laurent97ac8712018-07-27 18:59:02 -07002462 ALOGV("stopOutput() output %d, stream %d, session %d",
2463 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002464
Eric Laurent97ac8712018-07-27 18:59:02 -07002465 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002466
Eric Laurent733ce942017-12-07 12:18:25 -08002467 if (status == NO_ERROR ) {
2468 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002469 } else {
2470 return status;
2471 }
2472
2473 if (outputDesc->devices().size() == 1) {
2474 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2475 outputDesc->devices()[0]->getId(), client->strategy());
2476 if (info != nullptr && info->getUid() == client->uid()) {
2477 info->decreaseActiveClient();
2478 if (info->getActiveClientCount() == 0) {
2479 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2480 }
2481 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002482 }
2483 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002484}
2485
Eric Laurent97ac8712018-07-27 18:59:02 -07002486status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2487 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002488{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002489 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002490 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002491 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002492 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002493
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002494 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2495
François Gaffie1c878552018-11-22 16:53:21 +01002496 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2497 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002498 // Automatically disable the remote submix input when output is stopped on a
2499 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002500 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002501 if (isSingleDeviceType(
2502 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002503 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002504 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002505 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2506 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002507 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002508 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002509 }
2510 }
2511 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002512 if (client->hasPreferredDevice(true) &&
2513 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002514 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002515 forceDeviceUpdate = true;
2516 }
2517
Eric Laurente552edb2014-03-10 17:42:56 -07002518 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002519 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002520
Eric Laurente552edb2014-03-10 17:42:56 -07002521 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002522 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002523 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002524 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002525
2526 // If the routing does not change, if an output is routed on a device using HwGain
2527 // (aka setAudioPortConfig) and there are still active clients following different
2528 // volume group(s), force reapply volume
2529 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2530 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2531
Eric Laurente552edb2014-03-10 17:42:56 -07002532 // delay the device switch by twice the latency because stopOutput() is executed when
2533 // the track stop() command is received and at that time the audio track buffer can
2534 // still contain data that needs to be drained. The latency only covers the audio HAL
2535 // and kernel buffers. Also the latency does not always include additional delay in the
2536 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302537 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002538 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002539
2540 // force restoring the device selection on other active outputs if it differs from the
2541 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002542 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002543 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002544 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002545 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002546 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002547 desc->isActive() &&
2548 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002549 (newDevices != desc->devices())) {
2550 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2551 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002552
jiabin3ff8d7d2022-12-13 06:27:44 +00002553 if (desc->mUsePreferredMixerAttributes && force) {
2554 // If the device is using preferred mixer attributes, the output need to
2555 // reopen with default configuration when the new selected devices are
2556 // different from current routing devices.
2557 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2558 continue;
2559 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302560 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002561
Eric Laurent57de36c2016-09-28 16:59:11 -07002562 // re-apply device specific volume if not done by setOutputDevice()
2563 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002564 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002565 }
Eric Laurente552edb2014-03-10 17:42:56 -07002566 }
2567 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002568 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002569 // update the outputs if stopping one with a stream that can affect notification routing
2570 handleNotificationRoutingForStream(stream);
2571 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002572
2573 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2574 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002575 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002576 }
2577
François Gaffiec005e562018-11-06 15:04:49 +01002578 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002579 selectOutputForMusicEffects();
2580 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002581
2582 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2583
Eric Laurente552edb2014-03-10 17:42:56 -07002584 return NO_ERROR;
2585 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002586 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002587 return INVALID_OPERATION;
2588 }
2589}
2590
jiabinbce0c1d2020-10-05 11:20:18 -07002591bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002592{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002593 ALOGV("%s portId %d", __FUNCTION__, portId);
2594
2595 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2596 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002597 // If an output descriptor is closed due to a device routing change,
2598 // then there are race conditions with releaseOutput from tracks
2599 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2600 // destroyed shortly thereafter.
2601 //
2602 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002603 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002604 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002605 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002606
2607 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002608
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302609 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2610 if (outputDesc->isClientActive(client)) {
2611 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2612 stopOutput(portId);
2613 }
2614
Eric Laurent8fc147b2018-07-22 19:13:55 -07002615 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2616 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002617 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002618 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002619 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002620 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002621 if (--outputDesc->mDirectOpenCount == 0) {
2622 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002623 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002624 }
2625 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302626
Andy Hung39efb7a2018-09-26 15:39:28 -07002627 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002628 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2629 // The output is pending reopened to query dynamic profiles and
2630 // there is no active clients
2631 closeOutput(outputDesc->mIoHandle);
2632 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2633 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2634 if (newOutputDesc == nullptr) {
2635 ALOGE("%s failed to open output", __func__);
2636 }
2637 return true;
2638 }
2639 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002640}
2641
Eric Laurentcaf7f482014-11-25 17:50:47 -08002642status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2643 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002644 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002645 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002646 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002647 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002648 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002649 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002650 input_type_t *inputType,
2651 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002652{
François Gaffiec005e562018-11-06 15:04:49 +01002653 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002654 "flags %#x attributes=%s requested device ID %d",
2655 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2656 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002657
Eric Laurentad2e7b92017-09-14 20:06:42 -07002658 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002659 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002660 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002661 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002662 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002663 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002664 sp<RecordClientDescriptor> clientDesc;
2665 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002666 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002667 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002668
2669 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2670 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2671 return INVALID_OPERATION;
2672 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002673
Francois Gaffie716e1432019-01-14 16:58:59 +01002674 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2675 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002676 }
2677
Paul McLean466dc8e2015-04-17 13:15:36 -06002678 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002679 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002680 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002681
Eric Laurentad2e7b92017-09-14 20:06:42 -07002682 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2683 // possible
2684 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2685 *input != AUDIO_IO_HANDLE_NONE) {
2686 ssize_t index = mInputs.indexOfKey(*input);
2687 if (index < 0) {
2688 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2689 status = BAD_VALUE;
2690 goto error;
2691 }
2692 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002693 RecordClientVector clients = inputDesc->getClientsForSession(session);
2694 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002695 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2696 status = BAD_VALUE;
2697 goto error;
2698 }
2699 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2700 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002701 // corresponds to a new client and is only permitted from the same UID.
2702 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002703 if (clients.size() > 1) {
2704 for (const auto& client : clients) {
2705 // The client map is ordered by key values (portId) and portIds are allocated
2706 // incrementaly. So the first client in this list is the one opened by audio flinger
2707 // when the mmap stream is created and should be ignored as it does not correspond
2708 // to an actual client
2709 if (client == *clients.cbegin()) {
2710 continue;
2711 }
2712 if (uid != client->uid() && !client->isSilenced()) {
2713 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2714 uid, client->portId(), client->uid());
2715 status = INVALID_OPERATION;
2716 goto error;
2717 }
Eric Laurent331679c2018-04-16 17:03:16 -07002718 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002719 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002720 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002721 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002722
Eric Laurentfecbceb2021-02-09 14:46:43 +01002723 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002724 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002725 }
2726
2727 *input = AUDIO_IO_HANDLE_NONE;
2728 *inputType = API_INPUT_INVALID;
2729
Francois Gaffie716e1432019-01-14 16:58:59 +01002730 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002731 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002732 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002733 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002734 ALOGW("%s could not find input mix for attr %s",
2735 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002736 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002737 }
jiabinc1de2df2019-05-07 14:26:40 -07002738 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2739 String8(attr->tags + strlen("addr=")),
2740 AUDIO_FORMAT_DEFAULT);
2741 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002742 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002743 __func__, attributes.source, attributes.tags);
2744 status = BAD_VALUE;
2745 goto error;
2746 }
2747
Kevin Rocard25f9b052019-02-27 15:08:54 -08002748 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2749 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2750 } else {
2751 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2752 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002753 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002754 if (explicitRoutingDevice != nullptr) {
2755 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002756 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002757 // Prevent from storing invalid requested device id in clients
2758 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002759 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002760 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2761 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002762 }
François Gaffie11d30102018-11-02 16:09:09 +01002763 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002764 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002765 status = BAD_VALUE;
2766 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002767 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002768 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2769 *inputType = API_INPUT_MIX_CAPTURE;
2770 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002771 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2772 // there is an external policy, but this input is attached to a mix of recorders,
2773 // meaning it receives audio injected into the framework, so the recorder doesn't
2774 // know about it and is therefore considered "legacy"
2775 *inputType = API_INPUT_LEGACY;
2776 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002777 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002778 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002779 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002780 } else {
2781 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002782 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002783
Eric Laurent599c7582015-12-07 18:05:55 -08002784 }
2785
François Gaffiec005e562018-11-06 15:04:49 +01002786 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002787 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002788 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002789 AudioProfileVector profiles;
2790 status_t ret = getProfilesForDevices(
2791 DeviceVector(device), profiles, flags, true /*isInput*/);
2792 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002793 const auto channels = profiles[0]->getChannels();
2794 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2795 config->channel_mask = *channels.begin();
2796 }
2797 const auto sampleRates = profiles[0]->getSampleRates();
2798 if (!sampleRates.empty() &&
2799 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2800 config->sample_rate = *sampleRates.begin();
2801 }
jiabinf1c73972022-04-14 16:28:52 -07002802 config->format = profiles[0]->getFormat();
2803 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002804 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002805 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002806
Eric Laurent8f42ea12018-08-08 09:08:25 -07002807exit:
2808
François Gaffiec005e562018-11-06 15:04:49 +01002809 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2810 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002811
Francois Gaffie716e1432019-01-14 16:58:59 +01002812 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002813 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002814 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002815
Mikhail Naganov2996f672019-04-18 12:29:59 -07002816 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002817 requestedDeviceId, attributes.source, flags,
2818 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002819 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002820 // Move (if found) effect for the client session to its input
2821 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002822 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002823
2824 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2825 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002826
Eric Laurent599c7582015-12-07 18:05:55 -08002827 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002828
2829error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002830 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002831}
2832
2833
François Gaffie11d30102018-11-02 16:09:09 +01002834audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002835 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002836 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002837 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002838 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002839 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002840{
2841 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002842 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002843 bool isSoundTrigger = false;
2844
François Gaffiec005e562018-11-06 15:04:49 +01002845 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002846 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2847 if (index >= 0) {
2848 input = mSoundTriggerSessions.valueFor(session);
2849 isSoundTrigger = true;
2850 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2851 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2852 } else {
2853 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002854 }
François Gaffiec005e562018-11-06 15:04:49 +01002855 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002856 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002857 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002858 }
2859
Carter Hsua3abb402021-10-26 11:11:20 +08002860 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2861 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2862 }
2863
Eric Laurentfe231122017-11-17 17:48:06 -08002864 // sampling rate and flags may be updated by getInputProfile
2865 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2866 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002867 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002868 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002869 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002870 // find a compatible input profile (not necessarily identical in parameters)
2871 sp<IOProfile> profile = getInputProfile(
2872 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2873 if (profile == nullptr) {
2874 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002875 }
jiabin2fd710d2022-05-02 23:20:22 +00002876
Glenn Kasten05ddca52016-02-11 08:17:12 -08002877 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002878 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002879 if (samplingRate == 0) {
2880 samplingRate = profileSamplingRate;
2881 }
Eric Laurente552edb2014-03-10 17:42:56 -07002882
Eric Laurent322b4d22015-04-03 15:57:54 -07002883 if (profile->getModuleHandle() == 0) {
2884 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002885 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002886 }
2887
Eric Laurentec376dc2021-04-08 20:41:22 +02002888 // Reuse an already opened input if a client with the same session ID already exists
2889 // on that input
2890 for (size_t i = 0; i < mInputs.size(); i++) {
2891 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2892 if (desc->mProfile != profile) {
2893 continue;
2894 }
2895 RecordClientVector clients = desc->clientsList();
2896 for (const auto &client : clients) {
2897 if (session == client->session()) {
2898 return desc->mIoHandle;
2899 }
2900 }
2901 }
2902
Eric Laurent3974e3b2017-12-07 17:58:43 -08002903 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002904 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002905 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002906 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002907 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002908 continue;
2909 }
2910 // if sound trigger, reuse input if used by other sound trigger on same session
2911 // else
2912 // reuse input if active client app is not in IDLE state
2913 //
2914 RecordClientVector clients = desc->clientsList();
2915 bool doClose = false;
2916 for (const auto& client : clients) {
2917 if (isSoundTrigger != client->isSoundTrigger()) {
2918 continue;
2919 }
2920 if (client->isSoundTrigger()) {
2921 if (session == client->session()) {
2922 return desc->mIoHandle;
2923 }
2924 continue;
2925 }
2926 if (client->active() && client->appState() != APP_STATE_IDLE) {
2927 return desc->mIoHandle;
2928 }
2929 doClose = true;
2930 }
2931 if (doClose) {
2932 closeInput(desc->mIoHandle);
2933 } else {
2934 i++;
2935 }
2936 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002937 }
2938
Eric Laurentfe231122017-11-17 17:48:06 -08002939 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002940
Eric Laurentfe231122017-11-17 17:48:06 -08002941 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2942 lConfig.sample_rate = profileSamplingRate;
2943 lConfig.channel_mask = profileChannelMask;
2944 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002945
François Gaffie11d30102018-11-02 16:09:09 +01002946 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002947
2948 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002949 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002950 (profileSamplingRate != lConfig.sample_rate) ||
2951 !audio_formats_match(profileFormat, lConfig.format) ||
2952 (profileChannelMask != lConfig.channel_mask)) {
2953 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002954 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002955 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002956 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002957 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002958 }
Eric Laurent599c7582015-12-07 18:05:55 -08002959 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002960 }
2961
Eric Laurentc722f302014-12-10 11:21:49 -08002962 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002963
Eric Laurent599c7582015-12-07 18:05:55 -08002964 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002965 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002966
Eric Laurent599c7582015-12-07 18:05:55 -08002967 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002968}
2969
Eric Laurent4eb58f12018-12-07 16:41:02 -08002970status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002971{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002972 ALOGV("%s portId %d", __FUNCTION__, portId);
2973
2974 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2975 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002976 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002977 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002978 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002979 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002980 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002981 if (client->active()) {
2982 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2983 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002984 }
2985
Eric Laurent8f42ea12018-08-08 09:08:25 -07002986 audio_session_t session = client->session();
2987
Eric Laurent4eb58f12018-12-07 16:41:02 -08002988 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002989
Eric Laurent4eb58f12018-12-07 16:41:02 -08002990 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002991
Eric Laurent4eb58f12018-12-07 16:41:02 -08002992 status_t status = inputDesc->start();
2993 if (status != NO_ERROR) {
2994 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002995 }
Eric Laurente552edb2014-03-10 17:42:56 -07002996
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002997 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002998 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002999 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003000
Eric Laurent8f42ea12018-08-08 09:08:25 -07003001 // indicate active capture to sound trigger service if starting capture from a mic on
3002 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003003 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003004 if (device != nullptr) {
3005 status = setInputDevice(input, device, true /* force */);
3006 } else {
3007 ALOGW("%s no new input device can be found for descriptor %d",
3008 __FUNCTION__, inputDesc->getId());
3009 status = BAD_VALUE;
3010 }
Eric Laurente552edb2014-03-10 17:42:56 -07003011
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003012 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003013 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003014 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003015 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003016 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3017 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003018 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003019 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003020
François Gaffie11d30102018-11-02 16:09:09 +01003021 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3022 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003023 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003024 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003025 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003026
Eric Laurent8f42ea12018-08-08 09:08:25 -07003027 // automatically enable the remote submix output when input is started if not
3028 // used by a policy mix of type MIX_TYPE_RECORDERS
3029 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003030 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003031 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003032 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003033 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003034 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3035 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003036 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003037 if (address != "") {
3038 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3039 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003040 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003041 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003042 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003043 } else if (status != NO_ERROR) {
3044 // Restore client activity state.
3045 inputDesc->setClientActive(client, false);
3046 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003047 }
3048
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003049 ALOGV("%s input %d source = %d status = %d exit",
3050 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003051
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003052 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003053}
3054
Eric Laurent8fc147b2018-07-22 19:13:55 -07003055status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003056{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003057 ALOGV("%s portId %d", __FUNCTION__, portId);
3058
3059 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3060 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003061 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003062 return BAD_VALUE;
3063 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003064 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003065 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003066 if (!client->active()) {
3067 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003068 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003069 }
Carter Hsue6139d52021-07-08 10:30:20 +08003070 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003071 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003072
Eric Laurent8f42ea12018-08-08 09:08:25 -07003073 inputDesc->stop();
3074 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003075 auto current_source = inputDesc->source();
3076 setInputDevice(input, getNewInputDevice(inputDesc),
3077 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003078 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003079 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003080 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003081 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003082 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3083 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003084 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003085 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003086
3087 // automatically disable the remote submix output when input is stopped if not
3088 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003089 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003090 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003091 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003092 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003093 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3094 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003095 }
3096 if (address != "") {
3097 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3098 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003099 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003100 }
3101 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003102 resetInputDevice(input);
3103
3104 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3105 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003106 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3107 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003108 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003109 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003110 }
3111 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003112 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003113 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003114}
3115
Eric Laurent8fc147b2018-07-22 19:13:55 -07003116void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003117{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003118 ALOGV("%s portId %d", __FUNCTION__, portId);
3119
3120 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3121 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003122 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003123 return;
3124 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003125 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003126 audio_io_handle_t input = inputDesc->mIoHandle;
3127
Eric Laurent8f42ea12018-08-08 09:08:25 -07003128 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003129
Andy Hung39efb7a2018-09-26 15:39:28 -07003130 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003131 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003132 if (inputDesc->getClientCount() > 0) {
3133 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003134 return;
3135 }
3136
Eric Laurent05b90f82014-08-27 15:32:29 -07003137 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003138 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003139 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003140}
3141
Eric Laurent8f42ea12018-08-08 09:08:25 -07003142void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003143{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003144 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003145
3146 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003147 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003148 }
3149}
3150
Eric Laurent8f42ea12018-08-08 09:08:25 -07003151void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3152{
3153 stopInput(portId);
3154 releaseInput(portId);
3155}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003156
Eric Laurent0dd51852019-04-19 18:18:58 -07003157void AudioPolicyManager::checkCloseInputs() {
3158 // After connecting or disconnecting an input device, close input if:
3159 // - it has no client (was just opened to check profile) OR
3160 // - none of its supported devices are connected anymore OR
3161 // - one of its clients cannot be routed to one of its supported
3162 // devices anymore. Otherwise update device selection
3163 std::vector<audio_io_handle_t> inputsToClose;
3164 for (size_t i = 0; i < mInputs.size(); i++) {
3165 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3166 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003167 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003168 inputsToClose.push_back(mInputs.keyAt(i));
3169 } else {
3170 bool close = false;
3171 for (const auto& client : input->clientsList()) {
3172 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003173 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3174 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003175 if (!input->supportedDevices().contains(device)) {
3176 close = true;
3177 break;
3178 }
3179 }
3180 if (close) {
3181 inputsToClose.push_back(mInputs.keyAt(i));
3182 } else {
3183 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3184 }
3185 }
3186 }
3187
3188 for (const audio_io_handle_t handle : inputsToClose) {
3189 ALOGV("%s closing input %d", __func__, handle);
3190 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003191 }
Eric Laurentd4692962014-05-05 18:13:44 -07003192}
3193
François Gaffie251c7f02018-11-07 10:41:08 +01003194void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003195{
3196 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003197 if (indexMin < 0 || indexMax < 0) {
3198 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3199 return;
3200 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003201 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003202
3203 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003204 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3205 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003206 continue;
3207 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003208 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003209 }
Eric Laurente552edb2014-03-10 17:42:56 -07003210}
3211
Eric Laurente0720872014-03-11 09:30:41 -07003212status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003213 int index,
3214 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003215{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003216 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003217 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3218 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3219 return NO_ERROR;
3220 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003221 ALOGV("%s: stream %s attributes=%s", __func__,
3222 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003223 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003224}
3225
Eric Laurente0720872014-03-11 09:30:41 -07003226status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003227 int *index,
3228 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003229{
François Gaffiec005e562018-11-06 15:04:49 +01003230 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3231 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003232 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003233 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003234 deviceTypes = mEngine->getOutputDevicesForStream(
3235 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003236 }
jiabin9a3361e2019-10-01 09:38:30 -07003237 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003238}
3239
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003240status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003241 int index,
3242 audio_devices_t device)
3243{
3244 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003245 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3246 if (group == VOLUME_GROUP_NONE) {
3247 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003248 return BAD_VALUE;
3249 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003250 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003251 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003252 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003253 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003254 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3255 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3256 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3257 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003258 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3259
3260 status = setVolumeCurveIndex(index, device, curves);
3261 if (status != NO_ERROR) {
3262 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3263 return status;
3264 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003265
jiabin9a3361e2019-10-01 09:38:30 -07003266 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003267 auto curCurvAttrs = curves.getAttributes();
3268 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3269 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003270 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003271 } else if (!curves.getStreamTypes().empty()) {
3272 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003273 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003274 } else {
3275 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3276 return BAD_VALUE;
3277 }
jiabin9a3361e2019-10-01 09:38:30 -07003278 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3279 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003280
François Gaffiecfe17322018-11-07 13:41:29 +01003281 // update volume on all outputs and streams matching the following:
3282 // - The requested stream (or a stream matching for volume control) is active on the output
3283 // - The device (or devices) selected by the engine for this stream includes
3284 // the requested device
3285 // - For non default requested device, currently selected device on the output is either the
3286 // requested device or one of the devices selected by the engine for this stream
3287 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3288 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003289 for (size_t i = 0; i < mOutputs.size(); i++) {
3290 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003291 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003292
jiabin9a3361e2019-10-01 09:38:30 -07003293 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3294 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003295 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003296
3297 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003298 continue;
3299 }
3300 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3301 curDevices.find(device) == curDevices.end()) {
3302 continue;
3303 }
3304 bool applyVolume = false;
3305 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3306 curSrcDevices.insert(device);
3307 applyVolume = (curSrcDevices.find(
3308 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3309 } else {
3310 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3311 }
3312 if (!applyVolume) {
3313 continue; // next output
3314 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003315 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3316 // If a higher priority strategy is active, and the output is routed to a device with a
3317 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003318 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003319 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003320 // If the volume source is active with higher priority source, ensure at least Sw Muted
3321 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003322 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3323 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3324 false /*preferredDevice*/);
3325 if (activeClients.empty()) {
3326 continue;
3327 }
3328 bool isPreempted = false;
3329 bool isHigherPriority = productStrategy < strategy;
3330 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003331 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003332 ALOGV("%s: Strategy=%d (\nrequester:\n"
3333 " group %d, volumeGroup=%d attributes=%s)\n"
3334 " higher priority source active:\n"
3335 " volumeGroup=%d attributes=%s) \n"
3336 " on output %zu, bailing out", __func__, productStrategy,
3337 group, group, toString(attributes).c_str(),
3338 client->volumeSource(), toString(client->attributes()).c_str(), i);
3339 applyVolume = false;
3340 isPreempted = true;
3341 break;
3342 }
3343 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003344 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003345 applyVolume = true;
3346 }
3347 }
3348 if (isPreempted || applyVolume) {
3349 break;
3350 }
3351 }
3352 if (!applyVolume) {
3353 continue; // next output
3354 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003355 }
François Gaffieed91f582020-01-31 10:35:37 +01003356 //FIXME: workaround for truncated touch sounds
3357 // delayed volume change for system stream to be removed when the problem is
3358 // handled by system UI
3359 status_t volStatus = checkAndSetVolume(
3360 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003361 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003362 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3363 if (volStatus != NO_ERROR) {
3364 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003365 }
3366 }
François Gaffiecfe17322018-11-07 13:41:29 +01003367 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3368 return status;
3369}
3370
François Gaffieaaac0fd2018-11-22 17:56:39 +01003371status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003372 audio_devices_t device,
3373 IVolumeCurves &volumeCurves)
3374{
3375 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3376 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003377 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3378 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003379 (index > volumeCurves.getVolumeIndexMax())) {
3380 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3381 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3382 return BAD_VALUE;
3383 }
3384 if (!audio_is_output_device(device)) {
3385 return BAD_VALUE;
3386 }
3387
3388 // Force max volume if stream cannot be muted
3389 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3390
François Gaffieaaac0fd2018-11-22 17:56:39 +01003391 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003392 volumeCurves.addCurrentVolumeIndex(device, index);
3393 return NO_ERROR;
3394}
3395
3396status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3397 int &index,
3398 audio_devices_t device)
3399{
3400 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3401 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003402 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003403 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003404 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003405 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003406 }
jiabin9a3361e2019-10-01 09:38:30 -07003407 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003408}
3409
3410status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3411 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003412 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003413{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003414 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003415 return BAD_VALUE;
3416 }
jiabin9a3361e2019-10-01 09:38:30 -07003417 index = curves.getVolumeIndex(deviceTypes);
3418 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003419 return NO_ERROR;
3420}
3421
3422status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3423 int &index)
3424{
3425 index = getVolumeCurves(attr).getVolumeIndexMin();
3426 return NO_ERROR;
3427}
3428
3429status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3430 int &index)
3431{
3432 index = getVolumeCurves(attr).getVolumeIndexMax();
3433 return NO_ERROR;
3434}
3435
Eric Laurent36829f92017-04-07 19:04:42 -07003436audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003437{
3438 // select one output among several suitable for global effects.
3439 // The priority is as follows:
3440 // 1: An offloaded output. If the effect ends up not being offloadable,
3441 // AudioFlinger will invalidate the track and the offloaded output
3442 // will be closed causing the effect to be moved to a PCM output.
3443 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003444 // 3: The primary output
3445 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003446
François Gaffiec005e562018-11-06 15:04:49 +01003447 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3448 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003449 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003450
Eric Laurent36829f92017-04-07 19:04:42 -07003451 if (outputs.size() == 0) {
3452 return AUDIO_IO_HANDLE_NONE;
3453 }
Eric Laurente552edb2014-03-10 17:42:56 -07003454
Eric Laurent36829f92017-04-07 19:04:42 -07003455 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3456 bool activeOnly = true;
3457
3458 while (output == AUDIO_IO_HANDLE_NONE) {
3459 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3460 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3461 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3462
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003463 for (audio_io_handle_t output : outputs) {
3464 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003465 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003466 continue;
3467 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003468 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3469 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003470 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003471 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003472 }
3473 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003474 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003475 }
3476 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003477 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003478 }
3479 }
3480 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3481 output = outputOffloaded;
3482 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3483 output = outputDeepBuffer;
3484 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3485 output = outputPrimary;
3486 } else {
3487 output = outputs[0];
3488 }
3489 activeOnly = false;
3490 }
3491
3492 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003493 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3494 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003495 mMusicEffectOutput = output;
3496 }
3497
3498 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003499 return output;
3500}
3501
Eric Laurent36829f92017-04-07 19:04:42 -07003502audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3503{
3504 return selectOutputForMusicEffects();
3505}
3506
Eric Laurente0720872014-03-11 09:30:41 -07003507status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003508 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003509 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003510 int session,
3511 int id)
3512{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003513 if (session != AUDIO_SESSION_DEVICE) {
3514 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003515 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003516 index = mInputs.indexOfKey(io);
3517 if (index < 0) {
3518 ALOGW("registerEffect() unknown io %d", io);
3519 return INVALID_OPERATION;
3520 }
Eric Laurente552edb2014-03-10 17:42:56 -07003521 }
3522 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003523 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3524 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3525 || strategy == PRODUCT_STRATEGY_NONE));
3526 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003527}
3528
Eric Laurentc241b0d2018-11-28 09:08:49 -08003529status_t AudioPolicyManager::unregisterEffect(int id)
3530{
3531 if (mEffects.getEffect(id) == nullptr) {
3532 return INVALID_OPERATION;
3533 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003534 if (mEffects.isEffectEnabled(id)) {
3535 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3536 setEffectEnabled(id, false);
3537 }
3538 return mEffects.unregisterEffect(id);
3539}
3540
3541status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3542{
3543 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3544 if (effect == nullptr) {
3545 return INVALID_OPERATION;
3546 }
3547
3548 status_t status = mEffects.setEffectEnabled(id, enabled);
3549 if (status == NO_ERROR) {
3550 mInputs.trackEffectEnabled(effect, enabled);
3551 }
3552 return status;
3553}
3554
Eric Laurent6c796322019-04-09 14:13:17 -07003555
3556status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3557{
3558 mEffects.moveEffects(ids, io);
3559 return NO_ERROR;
3560}
3561
Eric Laurentc75307b2015-03-17 15:29:32 -07003562bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3563{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003564 auto vs = toVolumeSource(stream, false);
3565 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003566}
3567
3568bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3569{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003570 auto vs = toVolumeSource(stream, false);
3571 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003572}
3573
Eric Laurente0720872014-03-11 09:30:41 -07003574bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003575{
3576 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003577 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003578 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003579 return true;
3580 }
3581 }
3582 return false;
3583}
3584
Eric Laurent275e8e92014-11-30 15:14:47 -08003585// Register a list of custom mixes with their attributes and format.
3586// When a mix is registered, corresponding input and output profiles are
3587// added to the remote submix hw module. The profile contains only the
3588// parameters (sampling rate, format...) specified by the mix.
3589// The corresponding input remote submix device is also connected.
3590//
3591// When a remote submix device is connected, the address is checked to select the
3592// appropriate profile and the corresponding input or output stream is opened.
3593//
3594// When capture starts, getInputForAttr() will:
3595// - 1 look for a mix matching the address passed in attribtutes tags if any
3596// - 2 if none found, getDeviceForInputSource() will:
3597// - 2.1 look for a mix matching the attributes source
3598// - 2.2 if none found, default to device selection by policy rules
3599// At this time, the corresponding output remote submix device is also connected
3600// and active playback use cases can be transferred to this mix if needed when reconnecting
3601// after AudioTracks are invalidated
3602//
3603// When playback starts, getOutputForAttr() will:
3604// - 1 look for a mix matching the address passed in attribtutes tags if any
3605// - 2 if none found, look for a mix matching the attributes usage
3606// - 3 if none found, default to device and output selection by policy rules.
3607
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003608status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003609{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003610 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3611 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003612 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003613 sp<HwModule> rSubmixModule;
3614 // examine each mix's route type
3615 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003616 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003617 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3618 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3619 ALOGE("Unsupported Policy Mix %zu of %zu: "
3620 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3621 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003622 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003623 break;
3624 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003625 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3626 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003627 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003628 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3629 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003630 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003631 rSubmixModule = mHwModules.getModuleFromName(
3632 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3633 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003634 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003635 i);
3636 res = INVALID_OPERATION;
3637 break;
3638 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003639 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003640
Eric Laurent97ac8712018-07-27 18:59:02 -07003641 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003642 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003643 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003644 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003645 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3646 } else {
3647 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3648 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003649 }
François Gaffie036e1e92015-03-19 10:16:24 +01003650
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003651 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003652 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003653 res = INVALID_OPERATION;
3654 break;
3655 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003656 audio_config_t outputConfig = mix.mFormat;
3657 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003658 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3659 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003660 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3661 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003662 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003663 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003664 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003665 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003666
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003667 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003668 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003669 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003670 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003671 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003672 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003673 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003674 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3675 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003676 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003677 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003678 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003679
3680 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3681 mix.mDeviceType, mix.mDeviceAddress,
3682 String8(), AUDIO_FORMAT_DEFAULT);
3683 if (device == nullptr) {
3684 res = INVALID_OPERATION;
3685 break;
3686 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003687
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003688 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003689 // First try to find an already opened output supporting the device
3690 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003691 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003692
Eric Laurentc529cf62020-04-17 18:19:10 -07003693 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003694 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003695 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003696 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003697 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003698 } else {
3699 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003700 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003701 }
3702 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003703 // If no output found, try to find a direct output profile supporting the device
3704 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3705 sp<HwModule> module = mHwModules[i];
3706 for (size_t j = 0;
3707 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3708 j++) {
3709 sp<IOProfile> profile = module->getOutputProfiles()[j];
3710 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3711 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3712 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003713 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003714 res = INVALID_OPERATION;
3715 } else {
3716 foundOutput = true;
3717 }
3718 }
3719 }
3720 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003721 if (res != NO_ERROR) {
3722 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003723 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003724 res = INVALID_OPERATION;
3725 break;
3726 } else if (!foundOutput) {
3727 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003728 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003729 res = INVALID_OPERATION;
3730 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003731 } else {
3732 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003733 }
Eric Laurentc722f302014-12-10 11:21:49 -08003734 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003735 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003736 if (res != NO_ERROR) {
3737 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003738 } else if (checkOutputs) {
3739 checkForDeviceAndOutputChanges();
3740 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003741 }
3742 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003743}
3744
3745status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3746{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003747 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003748 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003749 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003750 sp<HwModule> rSubmixModule;
3751 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003752 for (const auto& mix : mixes) {
3753 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003754
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003755 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003756 rSubmixModule = mHwModules.getModuleFromName(
3757 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3758 if (rSubmixModule == 0) {
3759 res = INVALID_OPERATION;
3760 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003761 }
3762 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003763
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003764 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003765
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003766 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003767 res = INVALID_OPERATION;
3768 continue;
3769 }
3770
Kevin Rocard04ed0462019-05-02 17:53:24 -07003771 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003772 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003773 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3774 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003775 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003776 AUDIO_FORMAT_DEFAULT);
3777 if (res != OK) {
3778 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003779 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003780 }
3781 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003782 }
jiabin5740f082019-08-19 15:08:30 -07003783 rSubmixModule->removeOutputProfile(address.c_str());
3784 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003785
Kevin Rocard153f92d2018-12-18 18:33:28 -08003786 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003787 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003788 res = INVALID_OPERATION;
3789 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003790 } else {
3791 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003792 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003793 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003794 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003795 if (res == NO_ERROR && checkOutputs) {
3796 checkForDeviceAndOutputChanges();
3797 updateCallAndOutputRouting();
3798 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003799 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003800}
3801
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003802status_t AudioPolicyManager::updatePolicyMix(
3803 const AudioMix& mix,
3804 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3805 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3806 if (res == NO_ERROR) {
3807 checkForDeviceAndOutputChanges();
3808 updateCallAndOutputRouting();
3809 }
3810 return res;
3811}
3812
Mikhail Naganov100f0122018-11-29 11:22:16 -08003813void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3814{
3815 size_t i = 0;
3816 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3817 for (const auto& fmt : mManualSurroundFormats) {
3818 if (i++ != 0) dst->append(", ");
3819 std::string sfmt;
3820 FormatConverter::toString(fmt, sfmt);
3821 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3822 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3823 }
3824}
3825
Eric Laurentc529cf62020-04-17 18:19:10 -07003826// Returns true if all devices types match the predicate and are supported by one HW module
3827bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003828 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003829 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003830 const char *context,
3831 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003832 for (size_t i = 0; i < devices.size(); i++) {
3833 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003834 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003835 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003836 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003837 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003838 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003839 return false;
3840 }
3841 }
3842 return true;
3843}
3844
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003845void AudioPolicyManager::changeOutputDevicesMuteState(
3846 const AudioDeviceTypeAddrVector& devices) {
3847 ALOGVV("%s() num devices %zu", __func__, devices.size());
3848
3849 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3850 getSoftwareOutputsForDevices(devices);
3851
3852 for (size_t i = 0; i < outputs.size(); i++) {
3853 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3854 DeviceVector prevDevices = outputDesc->devices();
3855 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3856 }
3857}
3858
3859std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3860 const AudioDeviceTypeAddrVector& devices) const
3861{
3862 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3863 DeviceVector deviceDescriptors;
3864 for (size_t j = 0; j < devices.size(); j++) {
3865 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3866 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3867 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3868 ALOGE("%s: device type %#x address %s not supported or not an output device",
3869 __func__, devices[j].mType, devices[j].getAddress());
3870 continue;
3871 }
3872 deviceDescriptors.add(desc);
3873 }
3874 for (size_t i = 0; i < mOutputs.size(); i++) {
3875 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3876 continue;
3877 }
3878 outputs.push_back(mOutputs.valueAt(i));
3879 }
3880 return outputs;
3881}
3882
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003883status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003884 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003885 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003886 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3887 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003888 }
3889 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003890 if (res != NO_ERROR) {
3891 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3892 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003893 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003894
3895 checkForDeviceAndOutputChanges();
3896 updateCallAndOutputRouting();
3897
3898 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003899}
3900
3901status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3902 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003903 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3904 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003905 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003906 __FUNCTION__, uid);
3907 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003908 }
3909
Eric Laurentc529cf62020-04-17 18:19:10 -07003910 checkForDeviceAndOutputChanges();
3911 updateCallAndOutputRouting();
3912
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003913 return res;
3914}
3915
Eric Laurent2517af32020-11-25 15:31:27 +01003916
jiabin0a488932020-08-07 17:32:40 -07003917status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3918 device_role_t role,
3919 const AudioDeviceTypeAddrVector &devices) {
3920 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3921 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003922
Eric Laurentc529cf62020-04-17 18:19:10 -07003923 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003924 return BAD_VALUE;
3925 }
jiabin0a488932020-08-07 17:32:40 -07003926 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003927 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003928 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3929 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003930 return status;
3931 }
3932
3933 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003934
3935 bool forceVolumeReeval = false;
3936 // FIXME: workaround for truncated touch sounds
3937 // to be removed when the problem is handled by system UI
3938 uint32_t delayMs = 0;
3939 if (strategy == mCommunnicationStrategy) {
3940 forceVolumeReeval = true;
3941 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3942 updateInputRouting();
3943 }
3944 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003945
3946 return NO_ERROR;
3947}
3948
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003949void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
3950 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003951{
3952 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003953 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003954 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003955 // Only apply special touch sound delay once
3956 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003957 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003958 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003959 for (size_t i = 0; i < mOutputs.size(); i++) {
3960 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3961 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003962 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3963 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003964 // As done in setDeviceConnectionState, we could also fix default device issue by
3965 // preventing the force re-routing in case of default dev that distinguishes on address.
3966 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003967 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003968 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3969 // If the device is using preferred mixer attributes, the output need to reopen
3970 // with default configuration when the new selected devices are different from
3971 // current routing devices.
3972 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3973 continue;
3974 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05303975
3976 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
3977 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003978 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003979 // Only apply special touch sound delay once
3980 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003981 }
3982 if (forceVolumeReeval && !newDevices.isEmpty()) {
3983 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3984 }
3985 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003986 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01003987 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003988}
3989
Eric Laurent2517af32020-11-25 15:31:27 +01003990void AudioPolicyManager::updateInputRouting() {
3991 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303992 // Skip for hotword recording as the input device switch
3993 // is handled within sound trigger HAL
3994 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3995 continue;
3996 }
Eric Laurent2517af32020-11-25 15:31:27 +01003997 auto newDevice = getNewInputDevice(activeDesc);
3998 // Force new input selection if the new device can not be reached via current input
3999 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4000 setInputDevice(activeDesc->mIoHandle, newDevice);
4001 } else {
4002 closeInput(activeDesc->mIoHandle);
4003 }
4004 }
4005}
4006
Paul Wang5d7cdb52022-11-22 09:45:06 +00004007status_t
4008AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4009 device_role_t role,
4010 const AudioDeviceTypeAddrVector &devices) {
4011 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4012 dumpAudioDeviceTypeAddrVector(devices).c_str());
4013
Eric Laurent78fedbf2023-03-09 14:40:44 +01004014 if (!areAllDevicesSupported(
4015 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004016 return BAD_VALUE;
4017 }
4018 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4019 if (status != NO_ERROR) {
4020 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4021 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4022 return status;
4023 }
4024
4025 checkForDeviceAndOutputChanges();
4026
4027 bool forceVolumeReeval = false;
4028 // TODO(b/263479999): workaround for truncated touch sounds
4029 // to be removed when the problem is handled by system UI
4030 uint32_t delayMs = 0;
4031 if (strategy == mCommunnicationStrategy) {
4032 forceVolumeReeval = true;
4033 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4034 updateInputRouting();
4035 }
4036 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4037
4038 return NO_ERROR;
4039}
4040
4041status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4042 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004043{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004044 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004045
Paul Wang5d7cdb52022-11-22 09:45:06 +00004046 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004047 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004048 ALOGW_IF(status != NAME_NOT_FOUND,
4049 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004050 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004051 return status;
4052 }
4053
4054 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004055
4056 bool forceVolumeReeval = false;
4057 // FIXME: workaround for truncated touch sounds
4058 // to be removed when the problem is handled by system UI
4059 uint32_t delayMs = 0;
4060 if (strategy == mCommunnicationStrategy) {
4061 forceVolumeReeval = true;
4062 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4063 updateInputRouting();
4064 }
4065 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004066
4067 return NO_ERROR;
4068}
4069
jiabin0a488932020-08-07 17:32:40 -07004070status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4071 device_role_t role,
4072 AudioDeviceTypeAddrVector &devices) {
4073 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004074}
4075
Jiabin Huang3b98d322020-09-03 17:54:16 +00004076status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4077 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4078 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4079 dumpAudioDeviceTypeAddrVector(devices).c_str());
4080
Mikhail Naganov55773032020-10-01 15:08:13 -07004081 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004082 return BAD_VALUE;
4083 }
4084 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4085 ALOGW_IF(status != NO_ERROR,
4086 "Engine could not set preferred devices %s for audio source %d role %d",
4087 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4088
4089 return status;
4090}
4091
4092status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4093 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4094 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4095 dumpAudioDeviceTypeAddrVector(devices).c_str());
4096
Mikhail Naganov55773032020-10-01 15:08:13 -07004097 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004098 return BAD_VALUE;
4099 }
4100 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4101 ALOGW_IF(status != NO_ERROR,
4102 "Engine could not add preferred devices %s for audio source %d role %d",
4103 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4104
Eric Laurent2517af32020-11-25 15:31:27 +01004105 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004106 return status;
4107}
4108
4109status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4110 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4111{
4112 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4113 dumpAudioDeviceTypeAddrVector(devices).c_str());
4114
Eric Laurent78fedbf2023-03-09 14:40:44 +01004115 if (!areAllDevicesSupported(
4116 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004117 return BAD_VALUE;
4118 }
4119
4120 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4121 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004122 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004123 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004124 if (status == NO_ERROR) {
4125 updateInputRouting();
4126 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004127 return status;
4128}
4129
4130status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4131 device_role_t role) {
4132 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4133
4134 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004135 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004136 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004137 if (status == NO_ERROR) {
4138 updateInputRouting();
4139 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004140 return status;
4141}
4142
4143status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4144 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4145 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4146}
4147
Oscar Azucena90e77632019-11-27 17:12:28 -08004148status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004149 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004150 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004151 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4152 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004153 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004154 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4155 if (status != NO_ERROR) {
4156 ALOGE("%s() could not set device affinity for userId %d",
4157 __FUNCTION__, userId);
4158 return status;
4159 }
4160
4161 // reevaluate outputs for all devices
4162 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004163 changeOutputDevicesMuteState(devices);
4164 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4165 true /* skipDelays */);
4166 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004167
4168 return NO_ERROR;
4169}
4170
4171status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004172 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004173 AudioDeviceTypeAddrVector devices;
4174 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004175 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4176 if (status != NO_ERROR) {
4177 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4178 __FUNCTION__, userId);
4179 return status;
4180 }
4181
4182 // reevaluate outputs for all devices
4183 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004184 changeOutputDevicesMuteState(devices);
4185 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4186 true /* skipDelays */);
4187 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004188
4189 return NO_ERROR;
4190}
4191
Andy Hungc29d82b2018-10-05 12:23:17 -07004192void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004193{
Andy Hungc29d82b2018-10-05 12:23:17 -07004194 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004195 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004196 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004197 std::string stateLiteral;
4198 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004199 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004200 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4201 "communications", "media", "record", "dock", "system",
4202 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4203 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4204 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004205 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4206 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4207 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4208 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4209 dst->append(" (MANUAL: ");
4210 dumpManualSurroundFormats(dst);
4211 dst->append(")");
4212 }
4213 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004214 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004215 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4216 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004217 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004218 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004219
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004220 dst->append("\n");
4221 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4222 dst->append("\n");
4223 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004224 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004225 mOutputs.dump(dst);
4226 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004227 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004228 mAudioPatches.dump(dst);
4229 mPolicyMixes.dump(dst);
4230 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004231
Kevin Rocardb99cc752019-03-21 20:52:24 -07004232 dst->appendFormat(" AllowedCapturePolicies:\n");
4233 for (auto& policy : mAllowedCapturePolicies) {
4234 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4235 }
4236
jiabina84c3d32022-12-02 18:59:55 +00004237 dst->appendFormat(" Preferred mixer audio configuration:\n");
4238 for (const auto it : mPreferredMixerAttrInfos) {
4239 dst->appendFormat(" - device port id: %d\n", it.first);
4240 for (const auto preferredMixerInfoIt : it.second) {
4241 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4242 preferredMixerInfoIt.second->dump(dst);
4243 }
4244 }
4245
François Gaffiec005e562018-11-06 15:04:49 +01004246 dst->appendFormat("\nPolicy Engine dump:\n");
4247 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004248}
4249
4250status_t AudioPolicyManager::dump(int fd)
4251{
4252 String8 result;
4253 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004254 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004255 return NO_ERROR;
4256}
4257
Kevin Rocardb99cc752019-03-21 20:52:24 -07004258status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4259{
4260 mAllowedCapturePolicies[uid] = capturePolicy;
4261 return NO_ERROR;
4262}
4263
Eric Laurente552edb2014-03-10 17:42:56 -07004264// This function checks for the parameters which can be offloaded.
4265// This can be enhanced depending on the capability of the DSP and policy
4266// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004267audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004268{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004269 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004270 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004271 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004272 offloadInfo.format,
4273 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4274 offloadInfo.has_video);
4275
jiabin2b9d5a12021-12-10 01:06:29 +00004276 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004277 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004278 }
4279
4280 // See if there is a profile to support this.
4281 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004282 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004283 offloadInfo.sample_rate,
4284 offloadInfo.format,
4285 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004286 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4287 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004288 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4289 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4290 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004291 if (profile == nullptr) {
4292 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4293 }
4294 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4295 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4296 }
4297 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004298}
4299
Michael Chana94fbb22018-04-24 14:31:19 +10004300bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4301 const audio_attributes_t& attributes) {
4302 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004303 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004304 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4305 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004306 config.sample_rate,
4307 config.format,
4308 config.channel_mask,
4309 output_flags,
4310 true /* directOnly */);
4311 ALOGV("%s() profile %sfound with name: %s, "
4312 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4313 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004314 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004315 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004316
4317 // also try the MSD module if compatible profile not found
4318 if (profile == nullptr) {
4319 profile = getMsdProfileForOutput(outputDevices,
4320 config.sample_rate,
4321 config.format,
4322 config.channel_mask,
4323 output_flags,
4324 true /* directOnly */);
4325 ALOGV("%s() MSD profile %sfound with name: %s, "
4326 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4327 __FUNCTION__, profile != 0 ? "" : "NOT ",
4328 (profile != 0 ? profile->getTagName().c_str() : "null"),
4329 config.sample_rate, config.format, config.channel_mask, output_flags);
4330 }
4331 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004332}
4333
jiabin2b9d5a12021-12-10 01:06:29 +00004334bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4335 bool durationIgnored) {
4336 if (mMasterMono) {
4337 return false; // no offloading if mono is set.
4338 }
4339
4340 // Check if offload has been disabled
4341 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4342 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4343 return false;
4344 }
4345
4346 // Check if stream type is music, then only allow offload as of now.
4347 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4348 {
4349 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4350 return false;
4351 }
4352
4353 //TODO: enable audio offloading with video when ready
4354 const bool allowOffloadWithVideo =
4355 property_get_bool("audio.offload.video", false /* default_value */);
4356 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4357 ALOGV("%s: has_video == true, returning false", __func__);
4358 return false;
4359 }
4360
4361 //If duration is less than minimum value defined in property, return false
4362 const int min_duration_secs = property_get_int32(
4363 "audio.offload.min.duration.secs", -1 /* default_value */);
4364 if (!durationIgnored) {
4365 if (min_duration_secs >= 0) {
4366 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4367 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4368 __func__, min_duration_secs);
4369 return false;
4370 }
4371 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4372 ALOGV("%s: Offload denied by duration < default min(=%u)",
4373 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4374 return false;
4375 }
4376 }
4377
4378 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4379 // creating an offloaded track and tearing it down immediately after start when audioflinger
4380 // detects there is an active non offloadable effect.
4381 // FIXME: We should check the audio session here but we do not have it in this context.
4382 // This may prevent offloading in rare situations where effects are left active by apps
4383 // in the background.
4384 if (mEffects.isNonOffloadableEffectEnabled()) {
4385 return false;
4386 }
4387
4388 return true;
4389}
4390
4391audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4392 const audio_config_t *config) {
4393 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4394 offloadInfo.format = config->format;
4395 offloadInfo.sample_rate = config->sample_rate;
4396 offloadInfo.channel_mask = config->channel_mask;
4397 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4398 offloadInfo.has_video = false;
4399 offloadInfo.is_streaming = false;
4400 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4401
4402 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4403 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4404 audio_flags_to_audio_output_flags(attr->flags, &flags);
4405 // only retain flags that will drive compressed offload or passthrough
4406 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4407 if (offloadPossible) {
4408 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4409 }
4410 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4411
Dorin Drimusfae3c642022-03-17 18:36:30 +01004412 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004413 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004414 DeviceVector outputDevices = engineOutputDevices;
4415 // the MSD module checks for different conditions and output devices
4416 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4417 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4418 continue;
4419 }
4420 outputDevices = getMsdAudioOutDevices();
4421 }
jiabin2b9d5a12021-12-10 01:06:29 +00004422 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004423 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004424 config->sample_rate, nullptr /*updatedSamplingRate*/,
4425 config->format, nullptr /*updatedFormat*/,
4426 config->channel_mask, nullptr /*updatedChannelMask*/,
4427 flags)) {
4428 continue;
4429 }
4430 // reject profiles not corresponding to a device currently available
4431 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4432 continue;
4433 }
4434 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4435 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004436 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004437 != AUDIO_DIRECT_NOT_SUPPORTED) {
4438 // Already reports offload gapless supported. No need to report offload support.
4439 continue;
4440 }
4441 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4442 != AUDIO_OUTPUT_FLAG_NONE) {
4443 // If offload gapless is reported, no need to report offload support.
4444 directMode = (audio_direct_mode_t) ((directMode &
4445 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4446 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4447 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004448 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004449 }
4450 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004451 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004452 }
4453 }
4454 }
4455 return directMode;
4456}
4457
Dorin Drimusf2196d82022-01-03 12:11:18 +01004458status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4459 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004460 if (mEffects.isNonOffloadableEffectEnabled()) {
4461 return OK;
4462 }
jiabinf1c73972022-04-14 16:28:52 -07004463 DeviceVector devices;
4464 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004465 if (status != OK) {
4466 return status;
4467 }
4468 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4469 if (devices.empty()) {
4470 return OK; // no output devices for the attributes
4471 }
jiabinf1c73972022-04-14 16:28:52 -07004472 return getProfilesForDevices(devices, audioProfilesVector,
4473 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004474}
4475
jiabina84c3d32022-12-02 18:59:55 +00004476status_t AudioPolicyManager::getSupportedMixerAttributes(
4477 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4478 ALOGV("%s, portId=%d", __func__, portId);
4479 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4480 if (deviceDescriptor == nullptr) {
4481 ALOGE("%s the requested device is currently unavailable", __func__);
4482 return BAD_VALUE;
4483 }
jiabin96daffc2023-05-11 17:51:55 +00004484 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4485 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4486 deviceDescriptor->type());
4487 return BAD_VALUE;
4488 }
jiabina84c3d32022-12-02 18:59:55 +00004489 for (const auto& hwModule : mHwModules) {
4490 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4491 if (curProfile->supportsDevice(deviceDescriptor)) {
4492 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4493 }
4494 }
4495 }
4496 return NO_ERROR;
4497}
4498
4499status_t AudioPolicyManager::setPreferredMixerAttributes(
4500 const audio_attributes_t *attr,
4501 audio_port_handle_t portId,
4502 uid_t uid,
4503 const audio_mixer_attributes_t *mixerAttributes) {
4504 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4505 "mixerBehavior=%d}, uid=%d, portId=%u",
4506 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4507 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4508 mixerAttributes->mixer_behavior, uid, portId);
4509 if (attr->usage != AUDIO_USAGE_MEDIA) {
4510 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4511 return BAD_VALUE;
4512 }
4513 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4514 if (deviceDescriptor == nullptr) {
4515 ALOGE("%s the requested device is currently unavailable", __func__);
4516 return BAD_VALUE;
4517 }
4518 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4519 ALOGE("%s(%d), type=%d, is not a usb output device",
4520 __func__, portId, deviceDescriptor->type());
4521 return BAD_VALUE;
4522 }
4523
4524 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4525 audio_flags_to_audio_output_flags(attr->flags, &flags);
4526 flags = (audio_output_flags_t) (flags |
4527 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4528 sp<IOProfile> profile = nullptr;
4529 DeviceVector devices(deviceDescriptor);
4530 for (const auto& hwModule : mHwModules) {
4531 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4532 if (curProfile->hasDynamicAudioProfile()
4533 && curProfile->isCompatibleProfile(devices,
4534 mixerAttributes->config.sample_rate,
4535 nullptr /*updatedSamplingRate*/,
4536 mixerAttributes->config.format,
4537 nullptr /*updatedFormat*/,
4538 mixerAttributes->config.channel_mask,
4539 nullptr /*updatedChannelMask*/,
4540 flags,
4541 false /*exactMatchRequiredForInputFlags*/)) {
4542 profile = curProfile;
4543 break;
4544 }
4545 }
4546 }
4547 if (profile == nullptr) {
4548 ALOGE("%s, there is no compatible profile found", __func__);
4549 return BAD_VALUE;
4550 }
4551
4552 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4553 sp<PreferredMixerAttributesInfo>::make(
4554 uid, portId, profile, flags, *mixerAttributes);
4555 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4556 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4557
4558 // If 1) there is any client from the preferred mixer configuration owner that is currently
4559 // active and matches the strategy and 2) current output is on the preferred device and the
4560 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4561 // configuration.
4562 std::vector<audio_io_handle_t> outputsToReopen;
4563 for (size_t i = 0; i < mOutputs.size(); i++) {
4564 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004565 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4566 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4567 output->mUsePreferredMixerAttributes = true;
4568 } else {
4569 for (const auto &client: output->getActiveClients()) {
4570 if (client->uid() == uid && client->strategy() == strategy) {
4571 client->setIsInvalid();
4572 outputsToReopen.push_back(output->mIoHandle);
4573 }
jiabina84c3d32022-12-02 18:59:55 +00004574 }
4575 }
4576 }
4577 }
4578 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4579 config.sample_rate = mixerAttributes->config.sample_rate;
4580 config.channel_mask = mixerAttributes->config.channel_mask;
4581 config.format = mixerAttributes->config.format;
4582 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004583 sp<SwAudioOutputDescriptor> desc =
4584 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4585 if (desc == nullptr) {
4586 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4587 continue;
4588 }
4589 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004590 }
4591
4592 return NO_ERROR;
4593}
4594
4595sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004596 audio_port_handle_t devicePortId,
4597 product_strategy_t strategy,
4598 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004599 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4600 if (it == mPreferredMixerAttrInfos.end()) {
4601 return nullptr;
4602 }
jiabind9a58d32023-06-01 17:57:30 +00004603 if (activeBitPerfectPreferred) {
4604 for (auto [strategy, info] : it->second) {
4605 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4606 && info->getActiveClientCount() != 0) {
4607 return info;
4608 }
4609 }
jiabina84c3d32022-12-02 18:59:55 +00004610 }
jiabind9a58d32023-06-01 17:57:30 +00004611 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4612 return strategyMatchedMixerAttrInfoIt == it->second.end()
4613 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004614}
4615
4616status_t AudioPolicyManager::getPreferredMixerAttributes(
4617 const audio_attributes_t *attr,
4618 audio_port_handle_t portId,
4619 audio_mixer_attributes_t* mixerAttributes) {
4620 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4621 portId, mEngine->getProductStrategyForAttributes(*attr));
4622 if (info == nullptr) {
4623 return NAME_NOT_FOUND;
4624 }
4625 *mixerAttributes = info->getMixerAttributes();
4626 return NO_ERROR;
4627}
4628
4629status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4630 audio_port_handle_t portId,
4631 uid_t uid) {
4632 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4633 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4634 if (preferredMixerAttrInfo == nullptr) {
4635 return NAME_NOT_FOUND;
4636 }
4637 if (preferredMixerAttrInfo->getUid() != uid) {
4638 ALOGE("%s, requested uid=%d, owned uid=%d",
4639 __func__, uid, preferredMixerAttrInfo->getUid());
4640 return PERMISSION_DENIED;
4641 }
4642 mPreferredMixerAttrInfos[portId].erase(strategy);
4643 if (mPreferredMixerAttrInfos[portId].empty()) {
4644 mPreferredMixerAttrInfos.erase(portId);
4645 }
4646
4647 // Reconfig existing output
4648 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4649 for (size_t i = 0; i < mOutputs.size(); i++) {
4650 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4651 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4652 }
4653 }
4654 for (const auto output : potentialOutputsToReopen) {
4655 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4656 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4657 preferredMixerAttrInfo->getFlags())) {
4658 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4659 }
4660 }
4661 return NO_ERROR;
4662}
4663
Eric Laurent6a94d692014-05-20 11:18:06 -07004664status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4665 audio_port_type_t type,
4666 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004667 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004668 unsigned int *generation)
4669{
jiabin19cdba52020-11-24 11:28:58 -08004670 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4671 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004672 return BAD_VALUE;
4673 }
4674 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004675 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004676 *num_ports = 0;
4677 }
4678
4679 size_t portsWritten = 0;
4680 size_t portsMax = *num_ports;
4681 *num_ports = 0;
4682 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004683 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4684 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004685 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004686 for (const auto& dev : mAvailableOutputDevices) {
4687 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004688 continue;
4689 }
4690 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004691 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004692 }
4693 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004694 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004695 }
4696 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004697 for (const auto& dev : mAvailableInputDevices) {
4698 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004699 continue;
4700 }
4701 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004702 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004703 }
4704 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004705 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004706 }
4707 }
4708 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4709 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4710 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4711 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4712 }
4713 *num_ports += mInputs.size();
4714 }
4715 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004716 size_t numOutputs = 0;
4717 for (size_t i = 0; i < mOutputs.size(); i++) {
4718 if (!mOutputs[i]->isDuplicated()) {
4719 numOutputs++;
4720 if (portsWritten < portsMax) {
4721 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4722 }
4723 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004724 }
Eric Laurent84c70242014-06-23 08:46:27 -07004725 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004726 }
4727 }
jiabina84c3d32022-12-02 18:59:55 +00004728
Eric Laurent6a94d692014-05-20 11:18:06 -07004729 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004730 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004731 return NO_ERROR;
4732}
4733
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004734status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4735 std::vector<media::AudioPortFw>* _aidl_return) {
4736 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4737 audio_port_v7 port;
4738 dev->toAudioPort(&port);
4739 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4740 _aidl_return->push_back(std::move(aidlPort));
4741 return OK;
4742 };
4743
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004744 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004745 for (const auto& dev : module->getDeclaredDevices()) {
4746 if (role == media::AudioPortRole::NONE ||
4747 ((role == media::AudioPortRole::SOURCE)
4748 == audio_is_input_device(dev->type()))) {
4749 RETURN_STATUS_IF_ERROR(pushPort(dev));
4750 }
4751 }
4752 }
4753 return OK;
4754}
4755
jiabin19cdba52020-11-24 11:28:58 -08004756status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004757{
Eric Laurent99fcae42018-05-17 16:59:18 -07004758 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4759 return BAD_VALUE;
4760 }
4761 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4762 if (dev != 0) {
4763 dev->toAudioPort(port);
4764 return NO_ERROR;
4765 }
4766 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4767 if (dev != 0) {
4768 dev->toAudioPort(port);
4769 return NO_ERROR;
4770 }
4771 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4772 if (out != 0) {
4773 out->toAudioPort(port);
4774 return NO_ERROR;
4775 }
4776 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4777 if (in != 0) {
4778 in->toAudioPort(port);
4779 return NO_ERROR;
4780 }
4781 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004782}
4783
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004784status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4785 audio_patch_handle_t *handle,
4786 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004787{
François Gaffieafd4cea2019-11-18 15:50:22 +01004788 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004789 if (handle == NULL || patch == NULL) {
4790 return BAD_VALUE;
4791 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004792 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004793 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004794 return BAD_VALUE;
4795 }
4796 // only one source per audio patch supported for now
4797 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004798 return INVALID_OPERATION;
4799 }
Eric Laurent874c42872014-08-08 15:13:39 -07004800 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004801 return INVALID_OPERATION;
4802 }
Eric Laurent874c42872014-08-08 15:13:39 -07004803 for (size_t i = 0; i < patch->num_sinks; i++) {
4804 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4805 return INVALID_OPERATION;
4806 }
4807 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004808
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004809 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4810 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4811 if (srcDevice == nullptr || sinkDevice == nullptr) {
4812 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4813 return BAD_VALUE;
4814 }
4815 ALOGV("%s between source %s and sink %s", __func__,
4816 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4817 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4818 // Default attributes, default volume priority, not to infer with non raw audio patches.
4819 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4820 const struct audio_port_config *source = &patch->sources[0];
4821 sp<SourceClientDescriptor> sourceDesc =
4822 new InternalSourceClientDescriptor(
4823 portId, uid, attributes, *source, srcDevice, sinkDevice,
4824 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4825
4826 status_t status =
4827 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4828
4829 if (status != NO_ERROR) {
4830 return INVALID_OPERATION;
4831 }
4832 mAudioSources.add(portId, sourceDesc);
4833 return NO_ERROR;
4834}
4835
4836status_t AudioPolicyManager::connectAudioSourceToSink(
4837 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4838 const struct audio_patch *patch,
4839 audio_patch_handle_t &handle,
4840 uid_t uid, uint32_t delayMs)
4841{
4842 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4843 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4844 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4845 return INVALID_OPERATION;
4846 }
4847 sourceDesc->connect(handle, sinkDevice);
4848 if (isMsdPatch(handle)) {
4849 return NO_ERROR;
4850 }
4851 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4852 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4853 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4854 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4855 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4856 goto FailurePatchAdded;
4857 }
4858 status = swOutput->start();
4859 if (status != NO_ERROR) {
4860 goto FailureSourceAdded;
4861 }
4862 swOutput->addClient(sourceDesc);
4863 status = startSource(swOutput, sourceDesc, &delayMs);
4864 if (status != NO_ERROR) {
4865 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4866 goto FailureSourceActive;
4867 }
4868 if (delayMs != 0) {
4869 usleep(delayMs * 1000);
4870 }
4871 return NO_ERROR;
4872
4873FailureSourceActive:
4874 swOutput->stop();
4875 releaseOutput(sourceDesc->portId());
4876FailureSourceAdded:
4877 sourceDesc->setSwOutput(nullptr);
4878FailurePatchAdded:
4879 releaseAudioPatchInternal(handle);
4880 return INVALID_OPERATION;
4881}
4882
4883status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4884 audio_patch_handle_t *handle,
4885 uid_t uid, uint32_t delayMs,
4886 const sp<SourceClientDescriptor>& sourceDesc)
4887{
4888 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004889 sp<AudioPatch> patchDesc;
4890 ssize_t index = mAudioPatches.indexOfKey(*handle);
4891
François Gaffieafd4cea2019-11-18 15:50:22 +01004892 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4893 patch->sources[0].role,
4894 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004895#if LOG_NDEBUG == 0
4896 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004897 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4898 patch->sinks[i].role,
4899 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004900 }
4901#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004902
4903 if (index >= 0) {
4904 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004905 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4906 __func__, mUidCached, patchDesc->getUid(), uid);
4907 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004908 return INVALID_OPERATION;
4909 }
4910 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004911 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004912 }
4913
4914 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004915 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004916 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004917 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004918 return BAD_VALUE;
4919 }
Eric Laurent84c70242014-06-23 08:46:27 -07004920 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4921 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004922 if (patchDesc != 0) {
4923 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004924 ALOGV("%s source id differs for patch current id %d new id %d",
4925 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004926 return BAD_VALUE;
4927 }
4928 }
Eric Laurent874c42872014-08-08 15:13:39 -07004929 DeviceVector devices;
4930 for (size_t i = 0; i < patch->num_sinks; i++) {
4931 // Only support mix to devices connection
4932 // TODO add support for mix to mix connection
4933 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004934 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004935 return INVALID_OPERATION;
4936 }
4937 sp<DeviceDescriptor> devDesc =
4938 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4939 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004940 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004941 return BAD_VALUE;
4942 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004943
François Gaffie11d30102018-11-02 16:09:09 +01004944 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004945 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004946 NULL, // updatedSamplingRate
4947 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004948 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004949 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004950 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004951 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004952 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004953 return INVALID_OPERATION;
4954 }
4955 devices.add(devDesc);
4956 }
4957 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004958 return INVALID_OPERATION;
4959 }
Eric Laurent874c42872014-08-08 15:13:39 -07004960
Eric Laurent6a94d692014-05-20 11:18:06 -07004961 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004962 ALOGV("%s setting device %s on output %d",
4963 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304964 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004965 index = mAudioPatches.indexOfKey(*handle);
4966 if (index >= 0) {
4967 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004968 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004969 }
4970 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004971 patchDesc->setUid(uid);
4972 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004973 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004974 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004975 return INVALID_OPERATION;
4976 }
4977 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4978 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4979 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004980 // only one sink supported when connecting an input device to a mix
4981 if (patch->num_sinks > 1) {
4982 return INVALID_OPERATION;
4983 }
François Gaffie53615e22015-03-19 09:24:12 +01004984 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004985 if (inputDesc == NULL) {
4986 return BAD_VALUE;
4987 }
4988 if (patchDesc != 0) {
4989 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4990 return BAD_VALUE;
4991 }
4992 }
François Gaffie11d30102018-11-02 16:09:09 +01004993 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004994 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004995 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004996 return BAD_VALUE;
4997 }
4998
François Gaffie11d30102018-11-02 16:09:09 +01004999 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08005000 patch->sinks[0].sample_rate,
5001 NULL, /*updatedSampleRate*/
5002 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005003 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005004 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005005 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005006 // FIXME for the parameter type,
5007 // and the NONE
5008 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005009 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005010 return INVALID_OPERATION;
5011 }
5012 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005013 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005014 device->toString().c_str(), inputDesc->mIoHandle);
5015 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005016 index = mAudioPatches.indexOfKey(*handle);
5017 if (index >= 0) {
5018 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005019 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005020 }
5021 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005022 patchDesc->setUid(uid);
5023 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005024 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005025 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005026 return INVALID_OPERATION;
5027 }
5028 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5029 // device to device connection
5030 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005031 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005032 return BAD_VALUE;
5033 }
5034 }
François Gaffie11d30102018-11-02 16:09:09 +01005035 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005036 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005037 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005038 return BAD_VALUE;
5039 }
Eric Laurent874c42872014-08-08 15:13:39 -07005040
Eric Laurent6a94d692014-05-20 11:18:06 -07005041 //update source and sink with our own data as the data passed in the patch may
5042 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005043 PatchBuilder patchBuilder;
5044 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005045
5046 // if first sink is to MSD, establish single MSD patch
5047 if (getMsdAudioOutDevices().contains(
5048 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5049 ALOGV("%s patching to MSD", __FUNCTION__);
5050 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5051 goto installPatch;
5052 }
5053
François Gaffieafd4cea2019-11-18 15:50:22 +01005054 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5055 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005056
Eric Laurent874c42872014-08-08 15:13:39 -07005057 for (size_t i = 0; i < patch->num_sinks; i++) {
5058 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005059 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005060 return INVALID_OPERATION;
5061 }
François Gaffie11d30102018-11-02 16:09:09 +01005062 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005063 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005064 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005065 return BAD_VALUE;
5066 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005067 audio_port_config sinkPortConfig = {};
5068 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5069 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005070
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005071 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5072 // volume management purpose (tracking activity)
5073 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5074 // in config XML to reach the sink so that is can be declared as available.
5075 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005076 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005077 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005078 // take care of dynamic routing for SwOutput selection,
5079 audio_attributes_t attributes = sourceDesc->attributes();
5080 audio_stream_type_t stream = sourceDesc->stream();
5081 audio_attributes_t resultAttr;
5082 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5083 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005084 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5085 config.channel_mask =
5086 (audio_channel_mask_get_representation(sourceMask)
5087 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5088 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005089 config.format = sourceDesc->config().format;
5090 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5091 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5092 bool isRequestedDeviceForExclusiveUse = false;
5093 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005094 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005095 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005096 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5097 &stream, sourceDesc->uid(), &config, &flags,
5098 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005099 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005100 if (output == AUDIO_IO_HANDLE_NONE) {
5101 ALOGV("%s no output for device %s",
5102 __FUNCTION__, sinkDevice->toString().c_str());
5103 return INVALID_OPERATION;
5104 }
5105 outputDesc = mOutputs.valueFor(output);
5106 if (outputDesc->isDuplicated()) {
5107 ALOGE("%s output is duplicated", __func__);
5108 return INVALID_OPERATION;
5109 }
François Gaffie7e39df22022-04-26 12:48:49 +02005110 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5111 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005112 } else {
5113 // Same for "raw patches" aka created from createAudioPatch API
5114 SortedVector<audio_io_handle_t> outputs =
5115 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5116 // if the sink device is reachable via an opened output stream, request to
5117 // go via this output stream by adding a second source to the patch
5118 // description
5119 output = selectOutput(outputs);
5120 if (output == AUDIO_IO_HANDLE_NONE) {
5121 ALOGE("%s no output available for internal patch sink", __func__);
5122 return INVALID_OPERATION;
5123 }
5124 outputDesc = mOutputs.valueFor(output);
5125 if (outputDesc->isDuplicated()) {
5126 ALOGV("%s output for device %s is duplicated",
5127 __func__, sinkDevice->toString().c_str());
5128 return INVALID_OPERATION;
5129 }
François Gaffie7e39df22022-04-26 12:48:49 +02005130 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005131 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005132 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005133 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005134 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005135 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005136 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5137 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005138 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5139 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005140 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005141 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005142 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005143 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005144 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005145 return INVALID_OPERATION;
5146 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005147 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005148 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005149 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005150 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005151 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005152 srcMixPortConfig.ext.mix.usecase.stream =
5153 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005154 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5155 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005156 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005157 }
Eric Laurent83b88082014-06-20 18:31:16 -07005158 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005159 }
5160 // TODO: check from routing capabilities in config file and other conflicting patches
5161
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005162installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005163 status_t status = installPatch(
5164 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005165 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005166 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005167 return INVALID_OPERATION;
5168 }
5169 } else {
5170 return BAD_VALUE;
5171 }
5172 } else {
5173 return BAD_VALUE;
5174 }
5175 return NO_ERROR;
5176}
5177
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005178status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005179{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005180 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005181 ssize_t index = mAudioPatches.indexOfKey(handle);
5182
5183 if (index < 0) {
5184 return BAD_VALUE;
5185 }
5186 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005187 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5188 __func__, mUidCached, patchDesc->getUid(), uid);
5189 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005190 return INVALID_OPERATION;
5191 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005192 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5193 for (size_t i = 0; i < mAudioSources.size(); i++) {
5194 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5195 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5196 portId = sourceDesc->portId();
5197 break;
5198 }
5199 }
5200 return portId != AUDIO_PORT_HANDLE_NONE ?
5201 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005202}
Eric Laurent6a94d692014-05-20 11:18:06 -07005203
François Gaffieafd4cea2019-11-18 15:50:22 +01005204status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005205 uint32_t delayMs,
5206 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005207{
5208 ALOGV("%s patch %d", __func__, handle);
5209 if (mAudioPatches.indexOfKey(handle) < 0) {
5210 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5211 return BAD_VALUE;
5212 }
5213 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005214 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005215 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005216 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005217 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005218 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005219 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005220 return BAD_VALUE;
5221 }
5222
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305223 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005224 getNewOutputDevices(outputDesc, true /*fromCache*/),
5225 true,
5226 0,
5227 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005228 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5229 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005230 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005231 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005232 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005233 return BAD_VALUE;
5234 }
5235 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005236 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005237 true,
5238 NULL);
5239 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005240 status_t status =
5241 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5242 ALOGV("%s patch panel returned %d patchHandle %d",
5243 __func__, status, patchDesc->getAfHandle());
5244 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005245 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005246 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005247 // SW or HW Bridge
5248 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5249 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005250 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005251 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5252 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5253 outputDesc = sourceDesc->swOutput().promote();
5254 }
5255 if (outputDesc == nullptr) {
5256 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5257 // releaseOutput has already called closeOutput in case of direct output
5258 return NO_ERROR;
5259 }
François Gaffie7e39df22022-04-26 12:48:49 +02005260 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005261 // While using a HwBridge, force reconsidering device only if not reusing an existing
5262 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005263 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005264 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5265 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5266 // Reconsider device only for cases:
5267 // 1 / Active Output
5268 // 2 / Inactive Output previously hosting HwBridge
5269 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5270 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5271 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305272 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005273 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5274 outputDesc->devices(),
5275 force,
5276 0,
5277 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005278 } else {
5279 return BAD_VALUE;
5280 }
5281 } else {
5282 return BAD_VALUE;
5283 }
5284 return NO_ERROR;
5285}
5286
5287status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5288 struct audio_patch *patches,
5289 unsigned int *generation)
5290{
François Gaffie53615e22015-03-19 09:24:12 +01005291 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005292 return BAD_VALUE;
5293 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005294 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005295 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005296}
5297
Eric Laurente1715a42014-05-20 11:30:42 -07005298status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005299{
Eric Laurente1715a42014-05-20 11:30:42 -07005300 ALOGV("setAudioPortConfig()");
5301
5302 if (config == NULL) {
5303 return BAD_VALUE;
5304 }
5305 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5306 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005307 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5308 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005309 }
5310
Eric Laurenta121f902014-06-03 13:32:54 -07005311 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005312 if (config->type == AUDIO_PORT_TYPE_MIX) {
5313 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005314 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005315 if (outputDesc == NULL) {
5316 return BAD_VALUE;
5317 }
Eric Laurent84c70242014-06-23 08:46:27 -07005318 ALOG_ASSERT(!outputDesc->isDuplicated(),
5319 "setAudioPortConfig() called on duplicated output %d",
5320 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005321 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005322 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005323 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005324 if (inputDesc == NULL) {
5325 return BAD_VALUE;
5326 }
Eric Laurenta121f902014-06-03 13:32:54 -07005327 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005328 } else {
5329 return BAD_VALUE;
5330 }
5331 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5332 sp<DeviceDescriptor> deviceDesc;
5333 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5334 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5335 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5336 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5337 } else {
5338 return BAD_VALUE;
5339 }
5340 if (deviceDesc == NULL) {
5341 return BAD_VALUE;
5342 }
Eric Laurenta121f902014-06-03 13:32:54 -07005343 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005344 } else {
5345 return BAD_VALUE;
5346 }
5347
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005348 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005349 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5350 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005351 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005352 audioPortConfig->toAudioPortConfig(&newConfig, config);
5353 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005354 }
Eric Laurenta121f902014-06-03 13:32:54 -07005355 if (status != NO_ERROR) {
5356 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005357 }
Eric Laurente1715a42014-05-20 11:30:42 -07005358
5359 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005360}
5361
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005362void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5363{
Eric Laurentd60560a2015-04-10 11:31:20 -07005364 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005365 clearAudioPatches(uid);
5366 clearSessionRoutes(uid);
5367}
5368
Eric Laurent6a94d692014-05-20 11:18:06 -07005369void AudioPolicyManager::clearAudioPatches(uid_t uid)
5370{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005371 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005372 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005373 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005374 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005375 }
5376 }
5377}
5378
François Gaffiec005e562018-11-06 15:04:49 +01005379void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005380{
François Gaffiec005e562018-11-06 15:04:49 +01005381 // Take the first attributes following the product strategy as it is used to retrieve the routed
5382 // device. All attributes wihin a strategy follows the same "routing strategy"
5383 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5384 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005385 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005386 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005387 for (size_t j = 0; j < mOutputs.size(); j++) {
5388 if (mOutputs.keyAt(j) == ouptutToSkip) {
5389 continue;
5390 }
5391 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005392 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005393 continue;
5394 }
5395 // If the default device for this strategy is on another output mix,
5396 // invalidate all tracks in this strategy to force re connection.
5397 // Otherwise select new device on the output mix.
5398 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005399 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005400 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005401 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5402 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5403 // If the device is using preferred mixer attributes, the output need to reopen
5404 // with default configuration when the new selected devices are different from
5405 // current routing devices.
5406 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5407 continue;
5408 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305409 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005410 }
5411 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005412 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005413}
5414
5415void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5416{
5417 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005418 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005419 for (size_t i = 0; i < mOutputs.size(); i++) {
5420 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005421 for (const auto& client : outputDesc->getClientIterable()) {
5422 if (client->hasPreferredDevice() && client->uid() == uid) {
5423 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005424 auto clientStrategy = client->strategy();
5425 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5426 end(affectedStrategies)) {
5427 continue;
5428 }
5429 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005430 }
5431 }
5432 }
5433 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005434 for (const auto& strategy : affectedStrategies) {
5435 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005436 }
5437
5438 // remove input routes associated with this uid
5439 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005440 for (size_t i = 0; i < mInputs.size(); i++) {
5441 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005442 for (const auto& client : inputDesc->getClientIterable()) {
5443 if (client->hasPreferredDevice() && client->uid() == uid) {
5444 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5445 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005446 }
5447 }
5448 }
5449 // reroute inputs if necessary
5450 SortedVector<audio_io_handle_t> inputsToClose;
5451 for (size_t i = 0; i < mInputs.size(); i++) {
5452 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005453 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005454 inputsToClose.add(inputDesc->mIoHandle);
5455 }
5456 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005457 for (const auto& input : inputsToClose) {
5458 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005459 }
5460}
5461
Eric Laurentd60560a2015-04-10 11:31:20 -07005462void AudioPolicyManager::clearAudioSources(uid_t uid)
5463{
5464 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005465 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5466 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005467 stopAudioSource(mAudioSources.keyAt(i));
5468 }
5469 }
5470}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005471
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005472status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5473 audio_io_handle_t *ioHandle,
5474 audio_devices_t *device)
5475{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005476 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5477 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005478 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005479 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5480 if (deviceDesc == nullptr) {
5481 return INVALID_OPERATION;
5482 }
5483 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005484
François Gaffiedf372692015-03-19 10:43:27 +01005485 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005486}
5487
Eric Laurentd60560a2015-04-10 11:31:20 -07005488status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005489 const audio_attributes_t *attributes,
5490 audio_port_handle_t *portId,
5491 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005492{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005493 ALOGV("%s", __FUNCTION__);
5494 *portId = AUDIO_PORT_HANDLE_NONE;
5495
5496 if (source == NULL || attributes == NULL || portId == NULL) {
5497 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5498 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005499 return BAD_VALUE;
5500 }
5501
Eric Laurentd60560a2015-04-10 11:31:20 -07005502 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5503 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005504 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5505 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005506 return INVALID_OPERATION;
5507 }
5508
François Gaffie11d30102018-11-02 16:09:09 +01005509 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005510 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005511 String8(source->ext.device.address),
5512 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005513 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005514 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005515 return BAD_VALUE;
5516 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005517
jiabin4ef93452019-09-10 14:29:54 -07005518 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005519
François Gaffieaaac0fd2018-11-22 17:56:39 +01005520 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005521 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005522 mEngine->getStreamTypeForAttributes(*attributes),
5523 mEngine->getProductStrategyForAttributes(*attributes),
5524 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005525
5526 status_t status = connectAudioSource(sourceDesc);
5527 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005528 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005529 }
5530 return status;
5531}
5532
Francois Gaffie601801d2021-06-22 13:27:39 +02005533sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5534 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5535{
5536 ALOGV("%s", __FUNCTION__);
5537 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5538
5539 status_t status = startAudioSource(source, attributes, &portId, uid);
5540 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5541 return mAudioSources.valueFor(portId);
5542}
5543
5544
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005545status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005546{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005547 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005548
5549 // make sure we only have one patch per source.
5550 disconnectAudioSource(sourceDesc);
5551
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005552 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005553 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5554 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5555 sourceDesc->srcDevice()->type(),
5556 String8(sourceDesc->srcDevice()->address().c_str()),
5557 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005558 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005559 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005560 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005561 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005562 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5563 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5564 return INVALID_OPERATION;
5565 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005566 PatchBuilder patchBuilder;
5567 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5568 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005569
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005570 return connectAudioSourceToSink(
5571 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005572}
5573
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005574status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005575{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005576 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5577 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005578 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005579 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005580 return BAD_VALUE;
5581 }
5582 status_t status = disconnectAudioSource(sourceDesc);
5583
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005584 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005585 return status;
5586}
5587
Andy Hung2ddee192015-12-18 17:34:44 -08005588status_t AudioPolicyManager::setMasterMono(bool mono)
5589{
5590 if (mMasterMono == mono) {
5591 return NO_ERROR;
5592 }
5593 mMasterMono = mono;
5594 // if enabling mono we close all offloaded devices, which will invalidate the
5595 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5596 // for recreating the new AudioTrack as non-offloaded PCM.
5597 //
5598 // If disabling mono, we leave all tracks as is: we don't know which clients
5599 // and tracks are able to be recreated as offloaded. The next "song" should
5600 // play back offloaded.
5601 if (mMasterMono) {
5602 Vector<audio_io_handle_t> offloaded;
5603 for (size_t i = 0; i < mOutputs.size(); ++i) {
5604 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5605 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5606 offloaded.push(desc->mIoHandle);
5607 }
5608 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005609 for (const auto& handle : offloaded) {
5610 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005611 }
5612 }
5613 // update master mono for all remaining outputs
5614 for (size_t i = 0; i < mOutputs.size(); ++i) {
5615 updateMono(mOutputs.keyAt(i));
5616 }
5617 return NO_ERROR;
5618}
5619
5620status_t AudioPolicyManager::getMasterMono(bool *mono)
5621{
5622 *mono = mMasterMono;
5623 return NO_ERROR;
5624}
5625
Eric Laurentac9cef52017-06-09 15:46:26 -07005626float AudioPolicyManager::getStreamVolumeDB(
5627 audio_stream_type_t stream, int index, audio_devices_t device)
5628{
jiabin9a3361e2019-10-01 09:38:30 -07005629 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005630}
5631
jiabin81772902018-04-02 17:52:27 -07005632status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5633 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005634 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005635{
Kriti Dang6537def2021-03-02 13:46:59 +01005636 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5637 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005638 return BAD_VALUE;
5639 }
Kriti Dang6537def2021-03-02 13:46:59 +01005640 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5641 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005642
5643 size_t formatsWritten = 0;
5644 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005645
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005646 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005647 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5648 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005649 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005650 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005651 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005652 bool formatEnabled = true;
5653 switch (forceUse) {
5654 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005655 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005656 break;
5657 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5658 formatEnabled = false;
5659 break;
5660 default: // AUTO or ALWAYS => true
5661 break;
jiabin81772902018-04-02 17:52:27 -07005662 }
5663 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5664 }
jiabin81772902018-04-02 17:52:27 -07005665 }
5666 return NO_ERROR;
5667}
5668
Kriti Dang6537def2021-03-02 13:46:59 +01005669status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5670 audio_format_t *surroundFormats) {
5671 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5672 return BAD_VALUE;
5673 }
5674 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5675 __func__, *numSurroundFormats, surroundFormats);
5676
5677 size_t formatsWritten = 0;
5678 size_t formatsMax = *numSurroundFormats;
5679 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5680
5681 // Return formats from all device profiles that have already been resolved by
5682 // checkOutputsForDevice().
5683 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5684 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5685 audio_devices_t deviceType = device->type();
5686 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5687 // returns formats reported by HDMI devices.
5688 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5689 continue;
5690 }
5691 // Formats reported by sink devices
5692 std::unordered_set<audio_format_t> formatset;
5693 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5694 formatset.insert(it->second.begin(), it->second.end());
5695 }
5696
5697 // Formats hard-coded in the in policy configuration file (if any).
5698 FormatVector encodedFormats = device->encodedFormats();
5699 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5700 // Filter the formats which are supported by the vendor hardware.
5701 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005702 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005703 formats.insert(*it);
5704 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005705 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005706 if (pair.second.count(*it) != 0) {
5707 formats.insert(pair.first);
5708 break;
5709 }
5710 }
5711 }
5712 }
5713 }
5714 *numSurroundFormats = formats.size();
5715 for (const auto& format: formats) {
5716 if (formatsWritten < formatsMax) {
5717 surroundFormats[formatsWritten++] = format;
5718 }
5719 }
5720 return NO_ERROR;
5721}
5722
jiabin81772902018-04-02 17:52:27 -07005723status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5724{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005725 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005726 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5727 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005728 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005729 return BAD_VALUE;
5730 }
5731
Mikhail Naganov100f0122018-11-29 11:22:16 -08005732 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5733 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005734 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005735 return INVALID_OPERATION;
5736 }
5737
Mikhail Naganov100f0122018-11-29 11:22:16 -08005738 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005739 return NO_ERROR;
5740 }
5741
Mikhail Naganov100f0122018-11-29 11:22:16 -08005742 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005743 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005744 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005745 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005746 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005747 }
5748 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005749 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005750 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005751 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005752 }
5753 }
5754
5755 sp<SwAudioOutputDescriptor> outputDesc;
5756 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005757 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5758 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005759 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5760 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005761 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005762 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005763 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5764 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5765 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005766 name.c_str(),
5767 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005768 if (status != NO_ERROR) {
5769 continue;
5770 }
5771 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5772 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5773 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005774 name.c_str(),
5775 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005776 profileUpdated |= (status == NO_ERROR);
5777 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005778 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005779 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005780 AUDIO_DEVICE_IN_HDMI);
5781 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5782 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005783 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005784 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005785 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5786 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5787 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005788 name.c_str(),
5789 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005790 if (status != NO_ERROR) {
5791 continue;
5792 }
5793 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5794 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5795 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005796 name.c_str(),
5797 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005798 profileUpdated |= (status == NO_ERROR);
5799 }
5800
jiabin81772902018-04-02 17:52:27 -07005801 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005802 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005803 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005804 }
5805
5806 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5807}
5808
Eric Laurent5ada82e2019-08-29 17:53:54 -07005809void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005810{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005811 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005812 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005813 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005814 }
5815}
5816
jiabin6012f912018-11-02 17:06:30 -07005817bool AudioPolicyManager::isHapticPlaybackSupported()
5818{
5819 for (const auto& hwModule : mHwModules) {
5820 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5821 for (const auto &outProfile : outputProfiles) {
5822 struct audio_port audioPort;
5823 outProfile->toAudioPort(&audioPort);
5824 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5825 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5826 return true;
5827 }
5828 }
5829 }
5830 }
5831 return false;
5832}
5833
Carter Hsu325a8eb2022-01-19 19:56:51 +08005834bool AudioPolicyManager::isUltrasoundSupported()
5835{
5836 bool hasUltrasoundOutput = false;
5837 bool hasUltrasoundInput = false;
5838 for (const auto& hwModule : mHwModules) {
5839 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5840 if (!hasUltrasoundOutput) {
5841 for (const auto &outProfile : outputProfiles) {
5842 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5843 hasUltrasoundOutput = true;
5844 break;
5845 }
5846 }
5847 }
5848
5849 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5850 if (!hasUltrasoundInput) {
5851 for (const auto &inputProfile : inputProfiles) {
5852 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5853 hasUltrasoundInput = true;
5854 break;
5855 }
5856 }
5857 }
5858
5859 if (hasUltrasoundOutput && hasUltrasoundInput)
5860 return true;
5861 }
5862 return false;
5863}
5864
Atneya Nair698f5ef2022-12-15 16:15:09 -08005865bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5866{
5867 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5868 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5869 for (const auto& hwModule : mHwModules) {
5870 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5871 for (const auto &inputProfile : inputProfiles) {
5872 if ((inputProfile->getFlags() & mask) == mask) {
5873 return true;
5874 }
5875 }
5876 }
5877 return false;
5878}
5879
Eric Laurent8340e672019-11-06 11:01:08 -08005880bool AudioPolicyManager::isCallScreenModeSupported()
5881{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005882 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005883}
5884
5885
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005886status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005887{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005888 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005889 if (!sourceDesc->isConnected()) {
5890 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5891 return NO_ERROR;
5892 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005893 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5894 if (swOutput != 0) {
5895 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005896 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005897 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005898 }
jiabinbce0c1d2020-10-05 11:20:18 -07005899 if (releaseOutput(sourceDesc->portId())) {
5900 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5901 // no need to release audio patch here but just return NO_ERROR.
5902 return NO_ERROR;
5903 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005904 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005905 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005906 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005907 // close Hwoutput and remove from mHwOutputs
5908 } else {
5909 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5910 }
5911 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005912 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005913 sourceDesc->disconnect();
5914 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005915}
5916
François Gaffiec005e562018-11-06 15:04:49 +01005917sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5918 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005919{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005920 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005921 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005922 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005923 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005924 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5925 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005926 source = sourceDesc;
5927 break;
5928 }
5929 }
5930 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005931}
5932
Eric Laurentb4f42a92022-01-17 17:37:31 +01005933bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005934 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005935 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005936{
5937 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5938 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005939 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005940 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005941 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5942 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5943 return false;
5944 }
5945 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5946 return false;
5947 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005948 }
5949
Eric Laurentd332bc82023-08-04 11:45:23 +02005950 // The caller can have the audio config criteria ignored by either passing a null ptr or
5951 // the AUDIO_CONFIG_INITIALIZER value.
5952 // If an audio config is specified, current policy is to only allow spatialization for
5953 // some positional channel masks and PCM format
5954
5955 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
5956 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
5957 return false;
5958 }
5959 if (!audio_is_linear_pcm(config->format)) {
5960 return false;
5961 }
5962 }
5963
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005964 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005965 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005966 if (profile == nullptr) {
5967 return false;
5968 }
5969
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005970 return true;
5971}
5972
5973void AudioPolicyManager::checkVirtualizerClientRoutes() {
5974 std::set<audio_stream_type_t> streamsToInvalidate;
5975 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005976 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5977 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005978 audio_attributes_t attr = client->attributes();
5979 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5980 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5981 audio_config_base_t clientConfig = client->config();
5982 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005983 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005984 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005985 streamsToInvalidate.insert(client->stream());
5986 }
5987 }
5988 }
5989
jiabinc44b3462022-12-08 12:52:31 -08005990 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005991}
5992
Eric Laurente191d1b2022-04-15 11:59:25 +02005993
5994bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5995 const sp<SwAudioOutputDescriptor>& outputDesc) {
5996 if (outputDesc->isDuplicated()) {
5997 return false;
5998 }
5999 DeviceVector devices = outputDesc->supportedDevices();
6000 for (size_t i = 0; i < mOutputs.size(); i++) {
6001 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6002 if (desc == outputDesc || desc->isDuplicated()) {
6003 continue;
6004 }
6005 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6006 if (!sharedDevices.isEmpty()
6007 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6008 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6009 return false;
6010 }
6011 }
6012 return true;
6013}
6014
6015
Eric Laurentfa0f6742021-08-17 18:39:44 +02006016status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006017 const audio_attributes_t *attr,
6018 audio_io_handle_t *output) {
6019 *output = AUDIO_IO_HANDLE_NONE;
6020
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006021 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6022 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6023 audio_config_t *configPtr = nullptr;
6024 audio_config_t config;
6025 if (mixerConfig != nullptr) {
6026 config = audio_config_initializer(mixerConfig);
6027 configPtr = &config;
6028 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006029 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006030 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006031 return BAD_VALUE;
6032 }
6033
6034 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006035 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006036 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006037 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006038 return BAD_VALUE;
6039 }
6040
Eric Laurente191d1b2022-04-15 11:59:25 +02006041 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006042 for (size_t i = 0; i < mOutputs.size(); i++) {
6043 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006044 if (!desc->isDuplicated()
6045 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6046 spatializerOutputs.push_back(desc);
6047 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006048 }
6049 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006050 mSpatializerOutput.clear();
6051 bool outputsChanged = false;
6052 for (const auto& desc : spatializerOutputs) {
6053 if (desc->mProfile == profile
6054 && (configPtr == nullptr
6055 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6056 mSpatializerOutput = desc;
6057 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6058 } else {
6059 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6060 " and devices %s", __func__, desc->mIoHandle,
6061 configPtr != nullptr ? configPtr->channel_mask : 0,
6062 devices.toString().c_str());
6063 closeOutput(desc->mIoHandle);
6064 outputsChanged = true;
6065 }
Eric Laurent39095982021-08-24 18:29:27 +02006066 }
6067
Eric Laurente191d1b2022-04-15 11:59:25 +02006068 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006069 sp<SwAudioOutputDescriptor> desc =
6070 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006071 if (desc != nullptr) {
6072 mSpatializerOutput = desc;
6073 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006074 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006075 }
6076
6077 checkVirtualizerClientRoutes();
6078
Eric Laurente191d1b2022-04-15 11:59:25 +02006079 if (outputsChanged) {
6080 mPreviousOutputs = mOutputs;
6081 mpClientInterface->onAudioPortListUpdate();
6082 }
6083
6084 if (mSpatializerOutput == nullptr) {
6085 ALOGV("%s could not open spatializer output with requested config", __func__);
6086 return BAD_VALUE;
6087 }
Eric Laurent39095982021-08-24 18:29:27 +02006088 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006089 ALOGV("%s returning new spatializer output %d", __func__, *output);
6090 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006091}
6092
Eric Laurentfa0f6742021-08-17 18:39:44 +02006093status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6094 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006095 return INVALID_OPERATION;
6096 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006097 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006098 return BAD_VALUE;
6099 }
Eric Laurent39095982021-08-24 18:29:27 +02006100
Eric Laurente191d1b2022-04-15 11:59:25 +02006101 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6102 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6103 closeOutput(mSpatializerOutput->mIoHandle);
6104 //from now on mSpatializerOutput is null
6105 checkVirtualizerClientRoutes();
6106 }
Eric Laurent39095982021-08-24 18:29:27 +02006107
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006108 return NO_ERROR;
6109}
6110
Eric Laurente552edb2014-03-10 17:42:56 -07006111// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006112// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006113// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006114uint32_t AudioPolicyManager::nextAudioPortGeneration()
6115{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006116 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006117}
6118
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006119AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006120 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006121 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006122 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006123 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006124 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006125 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006126 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006127 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006128 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006129 mAudioPortGeneration(1),
6130 mBeaconMuteRefCount(0),
6131 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006132 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006133 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006134 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006135 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006136{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006137}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006138
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006139status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006140 if (mEngine == nullptr) {
6141 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006142 }
6143 mEngine->setObserver(this);
6144 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006145 if (status != NO_ERROR) {
6146 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6147 return status;
6148 }
François Gaffie2110e042015-03-24 08:41:51 +01006149
jiabin29230182023-04-04 21:02:36 +00006150 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6151 // at the end of this function.
6152 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006153 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6154 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6155
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006156 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006157 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006158 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006159
Eric Laurent3a4311c2014-03-17 12:00:47 -07006160 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006161 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6162 defaultOutputDevice == nullptr ||
6163 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6164 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6165 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006166 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006167 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006168 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006169
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006170 // Silence ALOGV statements
6171 property_set("log.tag." LOG_TAG, "D");
6172
Eric Laurente552edb2014-03-10 17:42:56 -07006173 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006174 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006175}
6176
Eric Laurente0720872014-03-11 09:30:41 -07006177AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006178{
Eric Laurente552edb2014-03-10 17:42:56 -07006179 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006180 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006181 }
6182 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006183 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006184 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006185 mAvailableOutputDevices.clear();
6186 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006187 mOutputs.clear();
6188 mInputs.clear();
6189 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006190 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006191 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006192}
6193
Eric Laurente0720872014-03-11 09:30:41 -07006194status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006195{
Eric Laurent87ffa392015-05-22 10:32:38 -07006196 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006197}
6198
Eric Laurente552edb2014-03-10 17:42:56 -07006199// ---
6200
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006201void AudioPolicyManager::onNewAudioModulesAvailable()
6202{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006203 DeviceVector newDevices;
6204 onNewAudioModulesAvailableInt(&newDevices);
6205 if (!newDevices.empty()) {
6206 nextAudioPortGeneration();
6207 mpClientInterface->onAudioPortListUpdate();
6208 }
6209}
6210
6211void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6212{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006213 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006214 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6215 continue;
6216 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006217 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006218 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6219 handle != AUDIO_MODULE_HANDLE_NONE) {
6220 hwModule->setHandle(handle);
6221 } else {
6222 ALOGW("could not load HW module %s", hwModule->getName());
6223 continue;
6224 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006225 }
6226 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006227 // open all output streams needed to access attached devices.
6228 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006229 // This also validates mAvailableOutputDevices list
6230 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6231 if (!outProfile->canOpenNewIo()) {
6232 ALOGE("Invalid Output profile max open count %u for profile %s",
6233 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6234 continue;
6235 }
6236 if (!outProfile->hasSupportedDevices()) {
6237 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6238 continue;
6239 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006240 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6241 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006242 mTtsOutputAvailable = true;
6243 }
6244
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006245 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006246 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006247 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006248 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6249 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006250 } else {
6251 // choose first device present in profile's SupportedDevices also part of
6252 // mAvailableOutputDevices.
6253 if (availProfileDevices.isEmpty()) {
6254 continue;
6255 }
6256 supportedDevice = availProfileDevices.itemAt(0);
6257 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006258 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006259 continue;
6260 }
6261 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6262 mpClientInterface);
6263 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006264 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6265 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006266 AUDIO_STREAM_DEFAULT,
6267 AUDIO_OUTPUT_FLAG_NONE, &output);
6268 if (status != NO_ERROR) {
6269 ALOGW("Cannot open output stream for devices %s on hw module %s",
6270 supportedDevice->toString().c_str(), hwModule->getName());
6271 continue;
6272 }
6273 for (const auto &device : availProfileDevices) {
6274 // give a valid ID to an attached device once confirmed it is reachable
6275 if (!device->isAttached()) {
6276 device->attach(hwModule);
6277 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006278 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006279 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006280 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6281 }
6282 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006283 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006284 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6285 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006286 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006287 }
Eric Laurent39095982021-08-24 18:29:27 +02006288 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006289 outputDesc->close();
6290 } else {
6291 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306292 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006293 DeviceVector(supportedDevice),
6294 true,
6295 0,
6296 NULL);
6297 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006298 }
6299 // open input streams needed to access attached devices to validate
6300 // mAvailableInputDevices list
6301 for (const auto& inProfile : hwModule->getInputProfiles()) {
6302 if (!inProfile->canOpenNewIo()) {
6303 ALOGE("Invalid Input profile max open count %u for profile %s",
6304 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6305 continue;
6306 }
6307 if (!inProfile->hasSupportedDevices()) {
6308 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6309 continue;
6310 }
6311 // chose first device present in profile's SupportedDevices also part of
6312 // available input devices
6313 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006314 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006315 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006316 ALOGV("%s: Input device list is empty! for profile %s",
6317 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006318 continue;
6319 }
6320 sp<AudioInputDescriptor> inputDesc =
6321 new AudioInputDescriptor(inProfile, mpClientInterface);
6322
6323 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6324 status_t status = inputDesc->open(nullptr,
6325 availProfileDevices.itemAt(0),
6326 AUDIO_SOURCE_MIC,
6327 AUDIO_INPUT_FLAG_NONE,
6328 &input);
6329 if (status != NO_ERROR) {
6330 ALOGW("Cannot open input stream for device %s on hw module %s",
6331 availProfileDevices.toString().c_str(),
6332 hwModule->getName());
6333 continue;
6334 }
6335 for (const auto &device : availProfileDevices) {
6336 // give a valid ID to an attached device once confirmed it is reachable
6337 if (!device->isAttached()) {
6338 device->attach(hwModule);
6339 device->importAudioPortAndPickAudioProfile(inProfile, true);
6340 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006341 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006342 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6343 }
6344 }
6345 inputDesc->close();
6346 }
6347 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006348
6349 // Check if spatializer outputs can be closed until used.
6350 // mOutputs vector never contains duplicated outputs at this point.
6351 std::vector<audio_io_handle_t> outputsClosed;
6352 for (size_t i = 0; i < mOutputs.size(); i++) {
6353 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6354 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6355 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6356 outputsClosed.push_back(desc->mIoHandle);
6357 desc->close();
6358 }
6359 }
6360 for (auto output : outputsClosed) {
6361 removeOutput(output);
6362 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006363}
6364
Eric Laurent98e38192018-02-15 18:31:53 -08006365void AudioPolicyManager::addOutput(audio_io_handle_t output,
6366 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006367{
Eric Laurent1c333e22014-05-20 10:48:17 -07006368 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006369 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006370 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006371 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006372 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006373}
6374
François Gaffie53615e22015-03-19 09:24:12 +01006375void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6376{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006377 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6378 ALOGV("%s: removing primary output", __func__);
6379 mPrimaryOutput = nullptr;
6380 }
François Gaffie53615e22015-03-19 09:24:12 +01006381 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006382 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006383}
6384
Eric Laurent98e38192018-02-15 18:31:53 -08006385void AudioPolicyManager::addInput(audio_io_handle_t input,
6386 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006387{
Eric Laurent1c333e22014-05-20 10:48:17 -07006388 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006389 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006390}
Eric Laurente552edb2014-03-10 17:42:56 -07006391
François Gaffie11d30102018-11-02 16:09:09 +01006392status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006393 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006394 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006395{
François Gaffie11d30102018-11-02 16:09:09 +01006396 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006397 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006398 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006399
François Gaffie11d30102018-11-02 16:09:09 +01006400 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006401 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006402 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006403 }
Eric Laurente552edb2014-03-10 17:42:56 -07006404
Eric Laurent3b73df72014-03-11 09:06:29 -07006405 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006406 // first call getAudioPort to get the supported attributes from the HAL
6407 struct audio_port_v7 port = {};
6408 device->toAudioPort(&port);
6409 status_t status = mpClientInterface->getAudioPort(&port);
6410 if (status == NO_ERROR) {
6411 device->importAudioPort(port);
6412 }
6413
6414 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006415 for (size_t i = 0; i < mOutputs.size(); i++) {
6416 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006417 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006418 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006419 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6420 mOutputs.keyAt(i), device->toString().c_str());
6421 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006422 }
6423 }
6424 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006425 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006426 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006427 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6428 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006429 if (profile->supportsDevice(device)) {
6430 profiles.add(profile);
6431 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6432 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006433 }
6434 }
6435 }
6436
Eric Laurent7b279bb2015-12-14 10:18:23 -08006437 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006438
Eric Laurente552edb2014-03-10 17:42:56 -07006439 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006440 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006441 return BAD_VALUE;
6442 }
6443
6444 // open outputs for matching profiles if needed. Direct outputs are also opened to
6445 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6446 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006447 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006448
6449 // nothing to do if one output is already opened for this profile
6450 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006451 for (j = 0; j < outputs.size(); j++) {
6452 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006453 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006454 // matching profile: save the sample rates, format and channel masks supported
6455 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006456 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006457 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006458 }
Eric Laurente552edb2014-03-10 17:42:56 -07006459 break;
6460 }
6461 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006462 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006463 continue;
6464 }
6465
Eric Laurent3974e3b2017-12-07 17:58:43 -08006466 if (!profile->canOpenNewIo()) {
6467 ALOGW("Max Output number %u already opened for this profile %s",
6468 profile->maxOpenCount, profile->getTagName().c_str());
6469 continue;
6470 }
6471
Eric Laurent83efe1c2017-07-09 16:51:08 -07006472 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006473 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006474 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6475 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006476 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006477 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006478 profiles.removeAt(profile_index);
6479 profile_index--;
6480 } else {
6481 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006482 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006483 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006484 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6485 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006486 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006487 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006488
François Gaffie11d30102018-11-02 16:09:09 +01006489 if (device_distinguishes_on_address(deviceType)) {
6490 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6491 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306492 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6493 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006494 }
Eric Laurente552edb2014-03-10 17:42:56 -07006495 ALOGV("checkOutputsForDevice(): adding output %d", output);
6496 }
6497 }
6498
6499 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006500 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006501 return BAD_VALUE;
6502 }
Eric Laurentd4692962014-05-05 18:13:44 -07006503 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006504 // check if one opened output is not needed any more after disconnecting one device
6505 for (size_t i = 0; i < mOutputs.size(); i++) {
6506 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006507 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006508 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006509 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006510 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006511 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006512 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006513 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6514 mOutputs.keyAt(i));
6515 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006516 }
Eric Laurente552edb2014-03-10 17:42:56 -07006517 }
6518 }
Eric Laurentd4692962014-05-05 18:13:44 -07006519 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006520 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006521 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6522 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006523 if (!profile->supportsDevice(device)) {
6524 continue;
6525 }
6526 ALOGV("checkOutputsForDevice(): "
6527 "clearing direct output profile %zu on module %s",
6528 j, hwModule->getName());
6529 profile->clearAudioProfiles();
6530 if (!profile->hasDynamicAudioProfile()) {
6531 continue;
6532 }
6533 // When a device is disconnected, if there is an IOProfile that contains dynamic
6534 // profiles and supports the disconnected device, call getAudioPort to repopulate
6535 // the capabilities of the devices that is supported by the IOProfile.
6536 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6537 if (supportedDevice == device ||
6538 !mAvailableOutputDevices.contains(supportedDevice)) {
6539 continue;
6540 }
6541 struct audio_port_v7 port;
6542 supportedDevice->toAudioPort(&port);
6543 status_t status = mpClientInterface->getAudioPort(&port);
6544 if (status == NO_ERROR) {
6545 supportedDevice->importAudioPort(port);
6546 }
Eric Laurente552edb2014-03-10 17:42:56 -07006547 }
6548 }
6549 }
6550 }
6551 return NO_ERROR;
6552}
6553
François Gaffie11d30102018-11-02 16:09:09 +01006554status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006555 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006556{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006557 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006558
François Gaffie11d30102018-11-02 16:09:09 +01006559 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006560 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006561 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006562 }
6563
Eric Laurentd4692962014-05-05 18:13:44 -07006564 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006565 // first call getAudioPort to get the supported attributes from the HAL
6566 struct audio_port_v7 port = {};
6567 device->toAudioPort(&port);
6568 status_t status = mpClientInterface->getAudioPort(&port);
6569 if (status == NO_ERROR) {
6570 device->importAudioPort(port);
6571 }
6572
Eric Laurent0dd51852019-04-19 18:18:58 -07006573 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006574 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006575 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006576 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006577 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006578 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006579 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006580
François Gaffie11d30102018-11-02 16:09:09 +01006581 if (profile->supportsDevice(device)) {
6582 profiles.add(profile);
6583 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6584 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006585 }
6586 }
6587 }
6588
Eric Laurent0dd51852019-04-19 18:18:58 -07006589 if (profiles.isEmpty()) {
6590 ALOGW("%s: No input profile available for device %s",
6591 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006592 return BAD_VALUE;
6593 }
6594
6595 // open inputs for matching profiles if needed. Direct inputs are also opened to
6596 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6597 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6598
Eric Laurent1c333e22014-05-20 10:48:17 -07006599 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006600
Eric Laurentd4692962014-05-05 18:13:44 -07006601 // nothing to do if one input is already opened for this profile
6602 size_t input_index;
6603 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6604 desc = mInputs.valueAt(input_index);
6605 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006606 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006607 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006608 }
Eric Laurentd4692962014-05-05 18:13:44 -07006609 break;
6610 }
6611 }
6612 if (input_index != mInputs.size()) {
6613 continue;
6614 }
6615
Eric Laurent3974e3b2017-12-07 17:58:43 -08006616 if (!profile->canOpenNewIo()) {
6617 ALOGW("Max Input number %u already opened for this profile %s",
6618 profile->maxOpenCount, profile->getTagName().c_str());
6619 continue;
6620 }
6621
Eric Laurentfe231122017-11-17 17:48:06 -08006622 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006623 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006624 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006625
Eric Laurentcf2c0212014-07-25 16:20:43 -07006626 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006627 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006628 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006629 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006630 mpClientInterface->setParameters(input, String8(param));
6631 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006632 }
François Gaffie11d30102018-11-02 16:09:09 +01006633 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006634 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006635 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006636 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006637 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006638 }
6639
Eric Laurent0dd51852019-04-19 18:18:58 -07006640 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006641 addInput(input, desc);
6642 }
6643 } // endif input != 0
6644
Eric Laurentcf2c0212014-07-25 16:20:43 -07006645 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006646 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006647 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006648 profiles.removeAt(profile_index);
6649 profile_index--;
6650 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006651 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006652 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006653 }
Eric Laurentd4692962014-05-05 18:13:44 -07006654 ALOGV("checkInputsForDevice(): adding input %d", input);
6655 }
6656 } // end scan profiles
6657
6658 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006659 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006660 return BAD_VALUE;
6661 }
6662 } else {
6663 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006664 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006665 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006666 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006667 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006668 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006669 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006670 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006671 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6672 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006673 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006674 }
6675 }
6676 }
6677 } // end disconnect
6678
6679 return NO_ERROR;
6680}
6681
6682
Eric Laurente0720872014-03-11 09:30:41 -07006683void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006684{
6685 ALOGV("closeOutput(%d)", output);
6686
François Gaffie1c878552018-11-22 16:53:21 +01006687 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6688 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006689 ALOGW("closeOutput() unknown output %d", output);
6690 return;
6691 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006692 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006693 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006694
Eric Laurente552edb2014-03-10 17:42:56 -07006695 // look for duplicated outputs connected to the output being removed.
6696 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006697 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6698 if (dupOutput->isDuplicated() &&
6699 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6700 sp<SwAudioOutputDescriptor> remainingOutput =
6701 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006702 // As all active tracks on duplicated output will be deleted,
6703 // and as they were also referenced on the other output, the reference
6704 // count for their stream type must be adjusted accordingly on
6705 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006706 const bool wasActive = remainingOutput->isActive();
6707 // Note: no-op on the closing output where all clients has already been set inactive
6708 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006709 // stop() will be a no op if the output is still active but is needed in case all
6710 // active streams refcounts where cleared above
6711 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006712 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006713 }
Eric Laurente552edb2014-03-10 17:42:56 -07006714 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6715 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6716
6717 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006718 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006719 }
6720 }
6721
Eric Laurent05b90f82014-08-27 15:32:29 -07006722 nextAudioPortGeneration();
6723
François Gaffie1c878552018-11-22 16:53:21 +01006724 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006725 if (index >= 0) {
6726 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006727 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6728 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006729 mAudioPatches.removeItemsAt(index);
6730 mpClientInterface->onAudioPatchListUpdate();
6731 }
6732
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006733 if (closingOutputWasActive) {
6734 closingOutput->stop();
6735 }
François Gaffie1c878552018-11-22 16:53:21 +01006736 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006737
François Gaffie53615e22015-03-19 09:24:12 +01006738 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006739 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006740 if (closingOutput == mSpatializerOutput) {
6741 mSpatializerOutput.clear();
6742 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006743
6744 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6745 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006746 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006747 bool directOutputOpen = false;
6748 for (size_t i = 0; i < mOutputs.size(); i++) {
6749 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6750 directOutputOpen = true;
6751 break;
6752 }
6753 }
6754 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006755 ALOGV("no direct outputs open, reset MSD patches");
6756 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6757 // how output devices for patching are resolved. Avoid by caching and reusing the
6758 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6759 // devices to patch to. This may be complicated by the fact that devices may become
6760 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006761 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006762 }
6763 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006764}
6765
6766void AudioPolicyManager::closeInput(audio_io_handle_t input)
6767{
6768 ALOGV("closeInput(%d)", input);
6769
6770 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6771 if (inputDesc == NULL) {
6772 ALOGW("closeInput() unknown input %d", input);
6773 return;
6774 }
6775
Eric Laurent6a94d692014-05-20 11:18:06 -07006776 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006777
François Gaffie11d30102018-11-02 16:09:09 +01006778 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006779 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006780 if (index >= 0) {
6781 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006782 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6783 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006784 mAudioPatches.removeItemsAt(index);
6785 mpClientInterface->onAudioPatchListUpdate();
6786 }
6787
François Gaffie6ebbce02023-07-19 13:27:53 +02006788 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006789 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006790 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006791
François Gaffie11d30102018-11-02 16:09:09 +01006792 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6793 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006794 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006795 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006796 }
Eric Laurente552edb2014-03-10 17:42:56 -07006797}
6798
François Gaffie11d30102018-11-02 16:09:09 +01006799SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6800 const DeviceVector &devices,
6801 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006802{
6803 SortedVector<audio_io_handle_t> outputs;
6804
François Gaffie11d30102018-11-02 16:09:09 +01006805 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006806 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006807 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006808 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006809 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006810 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006811 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006812 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006813 outputs.add(openOutputs.keyAt(i));
6814 }
6815 }
6816 return outputs;
6817}
6818
Mikhail Naganov37977152018-07-11 15:54:44 -07006819void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6820{
6821 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6822 // output is suspended before any tracks are moved to it
6823 checkA2dpSuspend();
6824 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006825 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006826 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006827 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006828 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006829 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6830 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6831 // configuration changes will ultimately be rerouted correctly. We can still avoid
6832 // unnecessary rerouting by caching and reusing the arguments to
6833 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6834 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006835 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006836 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006837 // an event that changed routing likely occurred, inform upper layers
6838 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006839}
6840
François Gaffiec005e562018-11-06 15:04:49 +01006841bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6842 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006843{
François Gaffiec005e562018-11-06 15:04:49 +01006844 return mEngine->getProductStrategyForAttributes(lAttr) ==
6845 mEngine->getProductStrategyForAttributes(rAttr);
6846}
6847
Francois Gaffieff1eb522020-05-06 18:37:04 +02006848void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6849{
6850 for (size_t i = 0; i < mAudioSources.size(); i++) {
6851 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6852 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006853 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006854 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006855 connectAudioSource(sourceDesc);
6856 }
6857 }
6858}
6859
6860void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6861{
6862 for (size_t i = 0; i < mAudioSources.size(); i++) {
6863 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6864 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6865 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6866 disconnectAudioSource(sourceDesc);
6867 }
6868 }
6869}
6870
François Gaffiec005e562018-11-06 15:04:49 +01006871void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6872{
6873 auto psId = mEngine->getProductStrategyForAttributes(attr);
6874
6875 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6876 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006877
François Gaffie11d30102018-11-02 16:09:09 +01006878 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6879 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006880
Eric Laurentc209fe42020-06-05 18:11:23 -07006881 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006882 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006883 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006884 // take into account dynamic audio policies related changes: if a client is now associated
6885 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006886 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006887 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6888 if (desc->isDuplicated()) {
6889 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006890 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006891 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6892 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6893 continue;
6894 }
6895 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006896 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006897 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6898 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6899 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006900 if (status != OK) {
6901 continue;
6902 }
yucliuf4de36d2020-09-14 14:57:56 -07006903 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006904 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006905 maxLatency = desc->latency();
6906 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006907 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006908 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006909 }
6910 }
6911
Eric Laurent56ed8842022-11-15 16:04:41 +01006912 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006913 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6914 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006915 for (audio_io_handle_t srcOut : srcOutputs) {
6916 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006917 if (desc == nullptr) continue;
6918
6919 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006920 maxLatency = desc->latency();
6921 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006922
Eric Laurent56ed8842022-11-15 16:04:41 +01006923 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006924 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006925 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006926 // a client on a non direct outputs has necessarily a linear PCM format
6927 // so we can call selectOutput() safely
6928 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6929 client->flags(),
6930 client->config().format,
6931 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006932 client->config().sample_rate,
6933 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006934 if (newOutput != srcOut) {
6935 invalidate = true;
6936 break;
6937 }
6938 } else {
6939 sp<IOProfile> profile = getProfileForOutput(newDevices,
6940 client->config().sample_rate,
6941 client->config().format,
6942 client->config().channel_mask,
6943 client->flags(),
6944 true /* directOnly */);
6945 if (profile != desc->mProfile) {
6946 invalidate = true;
6947 break;
6948 }
6949 }
6950 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006951 // mute strategy while moving tracks from one output to another
6952 if (invalidate) {
6953 invalidatedOutputs.push_back(desc);
6954 if (desc->isStrategyActive(psId)) {
6955 setStrategyMute(psId, true, desc);
6956 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6957 newDevices.types());
6958 }
Eric Laurente552edb2014-03-10 17:42:56 -07006959 }
François Gaffiec005e562018-11-06 15:04:49 +01006960 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006961 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006962 connectAudioSource(source);
6963 }
Eric Laurente552edb2014-03-10 17:42:56 -07006964 }
6965
Eric Laurent56ed8842022-11-15 16:04:41 +01006966 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6967 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6968 std::to_string(srcOutputs[0]).c_str(),
6969 std::to_string(dstOutputs[0]).c_str());
6970
François Gaffiec005e562018-11-06 15:04:49 +01006971 // Move effects associated to this stream from previous output to new output
6972 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006973 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006974 }
François Gaffiec005e562018-11-06 15:04:49 +01006975 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006976 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006977 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006978 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006979 desc->setTracksInvalidatedStatusByStrategy(psId);
6980 }
Eric Laurente552edb2014-03-10 17:42:56 -07006981 }
6982 }
6983}
6984
Eric Laurente0720872014-03-11 09:30:41 -07006985void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006986{
François Gaffiec005e562018-11-06 15:04:49 +01006987 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6988 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6989 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006990 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006991 }
Eric Laurente552edb2014-03-10 17:42:56 -07006992}
6993
Kevin Rocard153f92d2018-12-18 18:33:28 -08006994void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08006995 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006996 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006997 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006998 for (size_t i = 0; i < mOutputs.size(); i++) {
6999 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7000 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007001 sp<AudioPolicyMix> primaryMix;
7002 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007003 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007004 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7005 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7006 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007007 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7008 for (auto &secondaryMix : secondaryMixes) {
7009 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7010 if (outputDesc != nullptr &&
7011 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7012 secondaryDescs.push_back(outputDesc);
7013 }
7014 }
7015
jiabinc44b3462022-12-08 12:52:31 -08007016 if (status != OK &&
7017 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7018 // When it failed to query secondary output, only invalidate the client that is not
7019 // MMAP. The reason is that MMAP stream will not support secondary output.
7020 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007021 } else if (!std::equal(
7022 client->getSecondaryOutputs().begin(),
7023 client->getSecondaryOutputs().end(),
7024 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007025 if (!audio_is_linear_pcm(client->config().format)) {
7026 // If the format is not PCM, the tracks should be invalidated to get correct
7027 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007028 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007029 } else {
7030 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7031 std::vector<audio_io_handle_t> secondaryOutputIds;
7032 for (const auto &secondaryDesc: secondaryDescs) {
7033 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7034 weakSecondaryDescs.push_back(secondaryDesc);
7035 }
7036 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7037 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007038 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007039 }
7040 }
7041 }
jiabin10a03f12021-05-07 23:46:28 +00007042 if (!trackSecondaryOutputs.empty()) {
7043 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7044 }
jiabinc44b3462022-12-08 12:52:31 -08007045 if (!clientsToInvalidate.empty()) {
7046 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7047 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007048 }
7049}
7050
Eric Laurent2517af32020-11-25 15:31:27 +01007051bool AudioPolicyManager::isScoRequestedForComm() const {
7052 AudioDeviceTypeAddrVector devices;
7053 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7054 for (const auto &device : devices) {
7055 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7056 return true;
7057 }
7058 }
7059 return false;
7060}
7061
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007062bool AudioPolicyManager::isHearingAidUsedForComm() const {
7063 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7064 true /*fromCache*/);
7065 for (const auto &device : devices) {
7066 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7067 return true;
7068 }
7069 }
7070 return false;
7071}
7072
7073
Eric Laurente0720872014-03-11 09:30:41 -07007074void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007075{
François Gaffie53615e22015-03-19 09:24:12 +01007076 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007077 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007078 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007079 return;
7080 }
7081
Eric Laurent3a4311c2014-03-17 12:00:47 -07007082 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007083 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7084 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007085 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007086
7087 // if suspended, restore A2DP output if:
7088 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007089 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007090 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007091 //
Eric Laurentf732e072016-08-03 19:30:28 -07007092 // if not suspended, suspend A2DP output if:
7093 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007094 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007095 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007096 //
7097 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007098 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007099 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007100 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007101 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007102
7103 mpClientInterface->restoreOutput(a2dpOutput);
7104 mA2dpSuspended = false;
7105 }
7106 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007107 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007108 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007109 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007110 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007111
7112 mpClientInterface->suspendOutput(a2dpOutput);
7113 mA2dpSuspended = true;
7114 }
7115 }
7116}
7117
François Gaffie11d30102018-11-02 16:09:09 +01007118DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7119 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007120{
François Gaffiedb1755b2023-09-01 11:50:35 +02007121 if (outputDesc == nullptr) {
7122 return DeviceVector{};
7123 }
François Gaffie11d30102018-11-02 16:09:09 +01007124
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007125 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007126 if (index >= 0) {
7127 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007128 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007129 ALOGV("%s device %s forced by patch %d", __func__,
7130 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7131 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007132 }
7133 }
7134
Dean Wheatley514b4312020-06-17 21:45:00 +10007135 // Do not retrieve engine device for outputs through MSD
7136 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7137 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7138 return outputDesc->devices();
7139 }
7140
Eric Laurent97ac8712018-07-27 18:59:02 -07007141 // Honor explicit routing requests only if no client using default routing is active on this
7142 // input: a specific app can not force routing for other apps by setting a preferred device.
7143 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007144 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007145 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007146 if (device != nullptr) {
7147 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007148 }
7149
François Gaffiea807ef92018-11-05 10:44:33 +01007150 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7151 // of setForceUse / Default Bus device here
7152 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7153 if (device != nullptr) {
7154 return DeviceVector(device);
7155 }
7156
François Gaffiedb1755b2023-09-01 11:50:35 +02007157 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007158 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7159 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7160 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307161 auto hasStreamActive = [&](auto stream) {
7162 return hasStream(streams, stream) && isStreamActive(stream, 0);
7163 };
Eric Laurent484e9272018-06-07 17:29:23 -07007164
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307165 auto doGetOutputDevicesForVoice = [&]() {
7166 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007167 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307168 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007169 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7170 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307171 };
7172
7173 // With low-latency playing on speaker, music on WFD, when the first low-latency
7174 // output is stopped, getNewOutputDevices checks for a product strategy
7175 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007176 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307177 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7178 // stream is associated to the output descriptor.
7179 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7180 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7181 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7182 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007183 // Retrieval of devices for voice DL is done on primary output profile, cannot
7184 // check the route (would force modifying configuration file for this profile)
7185 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7186 break;
7187 }
Eric Laurente552edb2014-03-10 17:42:56 -07007188 }
François Gaffiec005e562018-11-06 15:04:49 +01007189 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007190 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007191}
7192
François Gaffie11d30102018-11-02 16:09:09 +01007193sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7194 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007195{
François Gaffie11d30102018-11-02 16:09:09 +01007196 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007197
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007198 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007199 if (index >= 0) {
7200 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007201 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007202 ALOGV("getNewInputDevice() device %s forced by patch %d",
7203 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7204 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007205 }
7206 }
7207
Eric Laurent97ac8712018-07-27 18:59:02 -07007208 // Honor explicit routing requests only if no client using default routing is active on this
7209 // input: a specific app can not force routing for other apps by setting a preferred device.
7210 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007211 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7212 if (device != nullptr) {
7213 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007214 }
7215
Eric Laurentdc95a252018-04-12 12:46:56 -07007216 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007217 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007218 audio_attributes_t attributes;
7219 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007220 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007221 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7222 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007223 attributes = topClient->attributes();
7224 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007225 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007226 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007227 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7228 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007229 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007230 }
7231
Francois Gaffie716e1432019-01-14 16:58:59 +01007232 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7233 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007234 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007235 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007236 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007237 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007238
Eric Laurente552edb2014-03-10 17:42:56 -07007239 return device;
7240}
7241
Eric Laurent794fde22016-03-11 09:50:45 -08007242bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7243 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007244 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007245}
7246
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007247status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007248 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007249 if (devices == nullptr) {
7250 return BAD_VALUE;
7251 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007252
Andy Hung6d23c0f2022-02-16 09:37:15 -08007253 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007254 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7255 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007256 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007257 for (const auto& device : curDevices) {
7258 devices->push_back(device->getDeviceTypeAddr());
7259 }
7260 return NO_ERROR;
7261}
7262
Eric Laurente0720872014-03-11 09:30:41 -07007263void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007264 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007265 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007266 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007267 updateDevicesAndOutputs();
7268 break;
7269 default:
7270 break;
7271 }
7272}
7273
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007274uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007275
7276 // skip beacon mute management if a dedicated TTS output is available
7277 if (mTtsOutputAvailable) {
7278 return 0;
7279 }
7280
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007281 switch(event) {
7282 case STARTING_OUTPUT:
7283 mBeaconMuteRefCount++;
7284 break;
7285 case STOPPING_OUTPUT:
7286 if (mBeaconMuteRefCount > 0) {
7287 mBeaconMuteRefCount--;
7288 }
7289 break;
7290 case STARTING_BEACON:
7291 mBeaconPlayingRefCount++;
7292 break;
7293 case STOPPING_BEACON:
7294 if (mBeaconPlayingRefCount > 0) {
7295 mBeaconPlayingRefCount--;
7296 }
7297 break;
7298 }
7299
7300 if (mBeaconMuteRefCount > 0) {
7301 // any playback causes beacon to be muted
7302 return setBeaconMute(true);
7303 } else {
7304 // no other playback: unmute when beacon starts playing, mute when it stops
7305 return setBeaconMute(mBeaconPlayingRefCount == 0);
7306 }
7307}
7308
7309uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7310 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7311 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7312 // keep track of muted state to avoid repeating mute/unmute operations
7313 if (mBeaconMuted != mute) {
7314 // mute/unmute AUDIO_STREAM_TTS on all outputs
7315 ALOGV("\t muting %d", mute);
7316 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007317 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7318 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7319 ALOGV("\t no tts volume source available");
7320 return 0;
7321 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007322 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007323 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007324 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007325 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007326 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007327 maxLatency = latency;
7328 }
7329 }
7330 mBeaconMuted = mute;
7331 return maxLatency;
7332 }
7333 return 0;
7334}
7335
Eric Laurente0720872014-03-11 09:30:41 -07007336void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007337{
François Gaffiec005e562018-11-06 15:04:49 +01007338 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007339 mPreviousOutputs = mOutputs;
7340}
7341
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007342uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007343 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007344 uint32_t delayMs)
7345{
7346 // mute/unmute strategies using an incompatible device combination
7347 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7348 // if unmuting, unmute only after the specified delay
7349 if (outputDesc->isDuplicated()) {
7350 return 0;
7351 }
7352
7353 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007354 DeviceVector devices = outputDesc->devices();
7355 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007356
François Gaffiec005e562018-11-06 15:04:49 +01007357 auto productStrategies = mEngine->getOrderedProductStrategies();
7358 for (const auto &productStrategy : productStrategies) {
7359 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7360 DeviceVector curDevices =
7361 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7362 curDevices = curDevices.filter(outputDesc->supportedDevices());
7363 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007364 bool doMute = false;
7365
François Gaffiec005e562018-11-06 15:04:49 +01007366 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007367 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007368 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7369 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007370 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007371 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007372 }
Eric Laurent99401132014-05-07 19:48:15 -07007373 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007374 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007375 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007376 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007377 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007378 continue;
7379 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307380 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007381 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7382 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7383 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007384 if (mute) {
7385 // FIXME: should not need to double latency if volume could be applied
7386 // immediately by the audioflinger mixer. We must account for the delay
7387 // between now and the next time the audioflinger thread for this output
7388 // will process a buffer (which corresponds to one buffer size,
7389 // usually 1/2 or 1/4 of the latency).
7390 if (muteWaitMs < desc->latency() * 2) {
7391 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007392 }
7393 }
7394 }
7395 }
7396 }
7397 }
7398
Eric Laurent99401132014-05-07 19:48:15 -07007399 // temporary mute output if device selection changes to avoid volume bursts due to
7400 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007401 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007402 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007403
Eric Laurentdc462862016-07-19 12:29:53 -07007404 if (muteWaitMs < tempMuteWaitMs) {
7405 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007406 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007407
7408 // If recommended duration is defined, replace temporary mute duration to avoid
7409 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7410 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7411 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7412 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7413 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7414
François Gaffieaaac0fd2018-11-22 17:56:39 +01007415 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7416 // make sure that we do not start the temporary mute period too early in case of
7417 // delayed device change
7418 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7419 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007420 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007421 }
7422 }
7423
Eric Laurente552edb2014-03-10 17:42:56 -07007424 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7425 if (muteWaitMs > delayMs) {
7426 muteWaitMs -= delayMs;
7427 usleep(muteWaitMs * 1000);
7428 return muteWaitMs;
7429 }
7430 return 0;
7431}
7432
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307433uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7434 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007435 const DeviceVector &devices,
7436 bool force,
7437 int delayMs,
7438 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007439 bool requiresMuteCheck, bool requiresVolumeCheck,
7440 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007441{
jiabin3ff8d7d2022-12-13 06:27:44 +00007442 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307443 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7444 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7445 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007446 uint32_t muteWaitMs;
7447
7448 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307449 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007450 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307451 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007452 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007453 return muteWaitMs;
7454 }
Eric Laurente552edb2014-03-10 17:42:56 -07007455
7456 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007457 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007458 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007459 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007460
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307461 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7462 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007463
7464 if (!filteredDevices.isEmpty()) {
7465 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007466 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007467
7468 // if the outputs are not materially active, there is no need to mute.
7469 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007470 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007471 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307472 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7473 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007474 muteWaitMs = 0;
7475 }
Eric Laurente552edb2014-03-10 17:42:56 -07007476
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007477 bool outputRouted = outputDesc->isRouted();
7478
Eric Laurent79ea9582020-06-11 18:49:24 -07007479 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7480 // output profile or if new device is not supported AND previous device(s) is(are) still
7481 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007482 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307483 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7484 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007485 // restore previous device after evaluating strategy mute state
7486 outputDesc->setDevices(prevDevices);
7487 return muteWaitMs;
7488 }
7489
Eric Laurente552edb2014-03-10 17:42:56 -07007490 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007491 // the requested device is AUDIO_DEVICE_NONE
7492 // OR the requested device is the same as current device
7493 // AND force is not specified
7494 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007495 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007496 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307497 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7498 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7499 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007500 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307501 ALOGV("%s %s setting same device on routed output, force apply volumes",
7502 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007503 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7504 }
Eric Laurente552edb2014-03-10 17:42:56 -07007505 return muteWaitMs;
7506 }
7507
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307508 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7509 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007510
Eric Laurente552edb2014-03-10 17:42:56 -07007511 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007512 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007513 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007514 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007515 PatchBuilder patchBuilder;
7516 patchBuilder.addSource(outputDesc);
7517 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7518 for (const auto &filteredDevice : filteredDevices) {
7519 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007520 }
7521
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007522 // Add half reported latency to delayMs when muteWaitMs is null in order
7523 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007524 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7525 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7526 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007527 }
Eric Laurente552edb2014-03-10 17:42:56 -07007528
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007529 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7530 if (!skipMuteDelay) {
7531 // update stream volumes according to new device
7532 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7533 }
Eric Laurente552edb2014-03-10 17:42:56 -07007534
7535 return muteWaitMs;
7536}
7537
Eric Laurentc75307b2015-03-17 15:29:32 -07007538status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007539 int delayMs,
7540 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007541{
Eric Laurent6a94d692014-05-20 11:18:06 -07007542 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007543 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7544 return INVALID_OPERATION;
7545 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007546 if (patchHandle) {
7547 index = mAudioPatches.indexOfKey(*patchHandle);
7548 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007549 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007550 }
7551 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007552 return INVALID_OPERATION;
7553 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007554 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007555 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007556 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007557 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007558 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007559 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007560 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007561 return status;
7562}
7563
7564status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007565 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007566 bool force,
7567 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007568{
7569 status_t status = NO_ERROR;
7570
Eric Laurent1f2f2232014-06-02 12:01:23 -07007571 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007572 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7573 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007574
François Gaffie11d30102018-11-02 16:09:09 +01007575 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007576 PatchBuilder patchBuilder;
7577 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007578 // AUDIO_SOURCE_HOTWORD is for internal use only:
7579 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007580 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7581 auto result = usecase;
7582 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7583 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7584 }
7585 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007586 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007587 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007588 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007589 }
7590 }
7591 return status;
7592}
7593
Eric Laurent6a94d692014-05-20 11:18:06 -07007594status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7595 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007596{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007597 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007598 ssize_t index;
7599 if (patchHandle) {
7600 index = mAudioPatches.indexOfKey(*patchHandle);
7601 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007602 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007603 }
7604 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007605 return INVALID_OPERATION;
7606 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007607 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007608 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007609 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007610 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007611 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007612 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007613 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007614 return status;
7615}
7616
François Gaffie11d30102018-11-02 16:09:09 +01007617sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007618 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007619 audio_format_t& format,
7620 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007621 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007622{
7623 // Choose an input profile based on the requested capture parameters: select the first available
7624 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007625 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007626 //
7627 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7628 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007629
Atneya Nair0f0a8032022-12-12 16:20:12 -08007630 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7631 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7632 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7633
7634 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007635
jiabin2fd710d2022-05-02 23:20:22 +00007636 for (;;) {
7637 sp<IOProfile> firstInexact = nullptr;
7638 uint32_t updatedSamplingRate = 0;
7639 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7640 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7641 for (const auto& hwModule : mHwModules) {
7642 for (const auto& profile : hwModule->getInputProfiles()) {
7643 // profile->log();
7644 //updatedFormat = format;
7645 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7646 &samplingRate /*updatedSamplingRate*/,
7647 format,
7648 &format, /*updatedFormat*/
7649 channelMask,
7650 &channelMask /*updatedChannelMask*/,
7651 // FIXME ugly cast
7652 (audio_output_flags_t) flags,
7653 true /*exactMatchRequiredForInputFlags*/)) {
7654 return profile;
7655 }
7656 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7657 samplingRate,
7658 &updatedSamplingRate,
7659 format,
7660 &updatedFormat,
7661 channelMask,
7662 &updatedChannelMask,
7663 // FIXME ugly cast
7664 (audio_output_flags_t) flags,
7665 false /*exactMatchRequiredForInputFlags*/)) {
7666 firstInexact = profile;
7667 }
7668 }
7669 }
7670
7671 if (firstInexact != nullptr) {
7672 samplingRate = updatedSamplingRate;
7673 format = updatedFormat;
7674 channelMask = updatedChannelMask;
7675 return firstInexact;
7676 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7677 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7678 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7679 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7680 flags = AUDIO_INPUT_FLAG_NONE;
7681 } else { // fail
7682 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7683 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7684 samplingRate, format, channelMask, oriFlags);
7685 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007686 }
7687 }
jiabin2fd710d2022-05-02 23:20:22 +00007688
7689 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007690}
7691
François Gaffieaaac0fd2018-11-22 17:56:39 +01007692float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7693 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007694 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007695 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007696{
jiabin9a3361e2019-10-01 09:38:30 -07007697 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007698
7699 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7700 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7701 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7702 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007703 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7704 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7705 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7706 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7707 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena437ded52023-08-30 18:45:18 -07007708 // Verify that the current volume source is not the ringer volume to prevent recursively
7709 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7710 // to the same volume group.
7711 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007712 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7713 mOutputs.isActive(ringVolumeSrc, 0)) {
7714 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007715 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007716 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007717 }
7718
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007719 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007720 if ((volumeSource != callVolumeSrc && (isInCall() ||
7721 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007722 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007723 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7724 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007725 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7726 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7727 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007728 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007729 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007730 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007731 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007732 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007733 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007734 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7735 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7736 // programmatically muted.
7737 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7738 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7739 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007740 bool exemptFromCapping =
7741 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7742 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007743 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7744 volumeSource, volumeDb);
7745 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007746 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7747 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7748 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007749 }
7750 }
Eric Laurente552edb2014-03-10 17:42:56 -07007751 // if a headset is connected, apply the following rules to ring tones and notifications
7752 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007753 // - always attenuate notifications volume by 6dB
7754 // - attenuate ring tones volume by 6dB unless music is not playing and
7755 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007756 // - if music is playing, always limit the volume to current music volume,
7757 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007758 if (!Intersection(deviceTypes,
7759 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7760 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007761 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7762 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007763 ((volumeSource == alarmVolumeSrc ||
7764 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007765 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7766 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7767 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007768 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7769 curves.canBeMuted()) {
7770
Eric Laurente552edb2014-03-10 17:42:56 -07007771 // when the phone is ringing we must consider that music could have been paused just before
7772 // by the music application and behave as if music was active if the last music track was
7773 // just stopped
Oscar Azucena437ded52023-08-30 18:45:18 -07007774 // Verify that the current volume source is not the music volume to prevent recursively
7775 // calling to compute volume. This could happen in cases where music and
7776 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7777 if (volumeSource != musicVolumeSrc &&
7778 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7779 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007780 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007781 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007782 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7783 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007784 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007785 float musicVolDb = computeVolume(musicCurves,
7786 musicVolumeSrc,
7787 musicCurves.getVolumeIndex(musicDevice),
7788 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007789 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7790 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7791 if (volumeDb > minVolDb) {
7792 volumeDb = minVolDb;
7793 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007794 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007795 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7796 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7797 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007798 // on A2DP, also ensure notification volume is not too low compared to media when
7799 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007800 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007801 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007802 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7803 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007804 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7805 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007806 }
7807 }
jiabin9a3361e2019-10-01 09:38:30 -07007808 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007809 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007810 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007811 }
7812 }
7813
François Gaffie43c73442018-11-08 08:21:55 +01007814 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007815}
7816
Eric Laurent3839bc02018-07-10 18:33:34 -07007817int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007818 VolumeSource fromVolumeSource,
7819 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007820{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007821 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007822 return srcIndex;
7823 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007824 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7825 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007826 float minSrc = (float)srcCurves.getVolumeIndexMin();
7827 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7828 float minDst = (float)dstCurves.getVolumeIndexMin();
7829 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007830
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007831 // preserve mute request or correct range
7832 if (srcIndex < minSrc) {
7833 if (srcIndex == 0) {
7834 return 0;
7835 }
7836 srcIndex = minSrc;
7837 } else if (srcIndex > maxSrc) {
7838 srcIndex = maxSrc;
7839 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007840 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7841}
7842
François Gaffieaaac0fd2018-11-22 17:56:39 +01007843status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7844 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007845 int index,
7846 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007847 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007848 int delayMs,
7849 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007850{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007851 // do not change actual attributes volume if the attributes is muted
7852 if (outputDesc->isMuted(volumeSource)) {
7853 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7854 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007855 return NO_ERROR;
7856 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007857 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7858 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7859 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7860 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007861
Eric Laurent2517af32020-11-25 15:31:27 +01007862 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007863 bool isHAUsed = isHearingAidUsedForComm();
7864
Eric Laurente552edb2014-03-10 17:42:56 -07007865 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007866 // if sco and call follow same curves, bypass forceUseForComm
7867 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007868 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007869 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7870 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007871 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007872 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007873 // Do not return an error here as AudioService will always set both voice call
7874 // and bluetooth SCO volumes due to stream aliasing.
7875 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007876 }
jiabin9a3361e2019-10-01 09:38:30 -07007877 if (deviceTypes.empty()) {
7878 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007879 index = curves.getVolumeIndex(deviceTypes);
7880 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7881 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007882 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007883
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007884 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7885 ALOGE("invalid volume index range");
7886 return BAD_VALUE;
7887 }
7888
jiabin9a3361e2019-10-01 09:38:30 -07007889 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7890 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007891 // Force VoIP volume to max for bluetooth SCO device except if muted
7892 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007893 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007894 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007895 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007896 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007897 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7898 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007899
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007900 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007901 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007902 // 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 +01007903 if (isVoiceVolSrc) {
7904 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007905 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007906 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007907 }
Eric Laurent18fba842016-03-31 14:41:26 -07007908 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007909 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7910 mLastVoiceVolume = voiceVolume;
7911 }
7912 }
Eric Laurente552edb2014-03-10 17:42:56 -07007913 return NO_ERROR;
7914}
7915
Eric Laurentc75307b2015-03-17 15:29:32 -07007916void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007917 const DeviceTypeSet& deviceTypes,
7918 int delayMs,
7919 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007920{
jiabincd510522020-01-22 09:40:55 -08007921 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007922 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7923 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7924 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007925 curves.getVolumeIndex(deviceTypes),
7926 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007927 }
7928}
7929
François Gaffiec005e562018-11-06 15:04:49 +01007930void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7931 bool on,
7932 const sp<AudioOutputDescriptor>& outputDesc,
7933 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007934 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007935{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007936 std::vector<VolumeSource> sourcesToMute;
7937 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7938 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7939 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007940 VolumeSource source = toVolumeSource(attributes, false);
7941 if ((source != VOLUME_SOURCE_NONE) &&
7942 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7943 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007944 sourcesToMute.push_back(source);
7945 }
Eric Laurente552edb2014-03-10 17:42:56 -07007946 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007947 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007948 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007949 }
7950
Eric Laurente552edb2014-03-10 17:42:56 -07007951}
7952
François Gaffieaaac0fd2018-11-22 17:56:39 +01007953void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7954 bool on,
7955 const sp<AudioOutputDescriptor>& outputDesc,
7956 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007957 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007958{
jiabin9a3361e2019-10-01 09:38:30 -07007959 if (deviceTypes.empty()) {
7960 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007961 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007962 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007963 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007964 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007965 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007966 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007967 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7968 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007969 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007970 }
7971 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007972 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7973 // ignored
7974 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007975 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007976 if (!outputDesc->isMuted(volumeSource)) {
7977 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007978 return;
7979 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007980 if (outputDesc->decMuteCount(volumeSource) == 0) {
7981 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007982 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007983 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007984 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007985 delayMs);
7986 }
7987 }
7988}
7989
François Gaffie53615e22015-03-19 09:24:12 +01007990bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7991{
François Gaffiec005e562018-11-06 15:04:49 +01007992 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007993 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7994 return true;
7995 }
7996
7997 // has known usage?
7998 switch (paa->usage) {
7999 case AUDIO_USAGE_UNKNOWN:
8000 case AUDIO_USAGE_MEDIA:
8001 case AUDIO_USAGE_VOICE_COMMUNICATION:
8002 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8003 case AUDIO_USAGE_ALARM:
8004 case AUDIO_USAGE_NOTIFICATION:
8005 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8006 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8007 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8008 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8009 case AUDIO_USAGE_NOTIFICATION_EVENT:
8010 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8011 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8012 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8013 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008014 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008015 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008016 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008017 case AUDIO_USAGE_EMERGENCY:
8018 case AUDIO_USAGE_SAFETY:
8019 case AUDIO_USAGE_VEHICLE_STATUS:
8020 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008021 break;
8022 default:
8023 return false;
8024 }
8025 return true;
8026}
8027
François Gaffie2110e042015-03-24 08:41:51 +01008028audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8029{
8030 return mEngine->getForceUse(usage);
8031}
8032
Eric Laurent96d1dda2022-03-14 17:14:19 +01008033bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008034 return isStateInCall(mEngine->getPhoneState());
8035}
8036
Eric Laurent96d1dda2022-03-14 17:14:19 +01008037bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008038 return is_state_in_call(state);
8039}
8040
Eric Laurentf9cccec2022-11-16 19:12:00 +01008041bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008042 audio_mode_t mode = mEngine->getPhoneState();
8043 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008044 || (mode == AUDIO_MODE_CALL_SCREEN)
8045 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008046}
8047
Eric Laurentf9cccec2022-11-16 19:12:00 +01008048bool AudioPolicyManager::isInCallOrScreening() const {
8049 audio_mode_t mode = mEngine->getPhoneState();
8050 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8051}
8052
Eric Laurentd60560a2015-04-10 11:31:20 -07008053void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8054{
8055 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008056 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008057 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008058 sourceDesc->sinkDevice()->equals(deviceDesc))
8059 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008060 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008061 }
8062 }
8063
8064 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8065 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8066 bool release = false;
8067 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8068 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8069 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8070 source->ext.device.type == deviceDesc->type()) {
8071 release = true;
8072 }
8073 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008074 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008075 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8076 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8077 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008078 sink->ext.device.type == deviceDesc->type() &&
8079 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8080 || strncmp(sink->ext.device.address, address,
8081 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008082 release = true;
8083 }
8084 }
8085 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008086 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8087 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008088 }
8089 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008090
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008091 mInputs.clearSessionRoutesForDevice(deviceDesc);
8092
Francois Gaffie716e1432019-01-14 16:58:59 +01008093 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008094}
8095
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008096void AudioPolicyManager::modifySurroundFormats(
8097 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008098 std::unordered_set<audio_format_t> enforcedSurround(
8099 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008100 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008101 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008102 allSurround.insert(pair.first);
8103 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8104 }
Phil Burk09bc4612016-02-24 15:58:15 -08008105
8106 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8107 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008108 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008109 // This is the resulting set of formats depending on the surround mode:
8110 // 'all surround' = allSurround
8111 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8112 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8113 // 'manual surround' = mManualSurroundFormats
8114 // AUTO: formats v 'enforced surround'
8115 // ALWAYS: formats v 'all surround' v 'enforced surround'
8116 // NEVER: formats ^ 'non-surround'
8117 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008118
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008119 std::unordered_set<audio_format_t> formatSet;
8120 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8121 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008122 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008123 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008124 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008125 formatSet.insert(*formatIter);
8126 }
8127 }
8128 } else {
8129 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8130 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008131 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008132
jiabin81772902018-04-02 17:52:27 -07008133 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008134 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008135 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8136 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8137 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008138 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008139 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8140 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8141 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008142 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008143 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008144 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008145 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008146 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008147 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008148}
8149
jiabin06e4bab2019-07-29 10:13:34 -07008150void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8151 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008152 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8153 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8154
8155 // If NEVER, then remove support for channelMasks > stereo.
8156 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008157 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8158 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008159 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008160 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008161 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008162 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008163 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008164 }
8165 }
jiabin81772902018-04-02 17:52:27 -07008166 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8167 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8168 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008169 bool supports5dot1 = false;
8170 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008171 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008172 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8173 supports5dot1 = true;
8174 break;
8175 }
8176 }
8177 // If not then add 5.1 support.
8178 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008179 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008180 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008181 }
Phil Burk09bc4612016-02-24 15:58:15 -08008182 }
8183}
8184
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008185void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008186 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01008187 AudioProfileVector &profiles)
8188{
8189 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008190 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07008191
François Gaffie112b0af2015-11-19 16:13:25 +01008192 // Format MUST be checked first to update the list of AudioProfile
8193 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008194 reply = mpClientInterface->getParameters(
8195 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008196 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.c_str());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008197 AudioParameter repliedParameters(reply);
jiabinf26596b2023-04-12 18:56:39 +00008198 FormatVector formats;
Eric Laurent62e4bc52016-02-02 18:37:28 -08008199 if (repliedParameters.get(
jiabinf26596b2023-04-12 18:56:39 +00008200 String8(AudioParameter::keyStreamSupportedFormats), reply) == NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008201 formats = formatsFromString(reply.c_str());
jiabinf26596b2023-04-12 18:56:39 +00008202 } else if (devDesc->hasValidAudioProfile()) {
8203 ALOGD("%s: using the device profiles", __func__);
8204 formats = devDesc->getAudioProfiles().getSupportedFormats();
8205 } else {
8206 ALOGE("%s: failed to retrieve format, bailing out", __func__);
François Gaffie112b0af2015-11-19 16:13:25 +01008207 return;
8208 }
Kriti Dangef6be8f2020-11-05 11:58:19 +01008209 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08008210 if (device == AUDIO_DEVICE_OUT_HDMI
8211 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008212 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07008213 }
jiabin3e277cc2019-09-10 14:27:34 -07008214 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01008215 }
François Gaffie112b0af2015-11-19 16:13:25 +01008216
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008217 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabinf26596b2023-04-12 18:56:39 +00008218 std::optional<ChannelMaskSet> channelMasks;
jiabin06e4bab2019-07-29 10:13:34 -07008219 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01008220 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07008221 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01008222
8223 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008224 reply = mpClientInterface->getParameters(
8225 ioHandle,
8226 requestedParameters.toString() + ";" +
8227 AudioParameter::keyStreamSupportedSamplingRates);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008228 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.c_str());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008229 AudioParameter repliedParameters(reply);
8230 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008231 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008232 samplingRates = samplingRatesFromString(reply.c_str());
jiabinf26596b2023-04-12 18:56:39 +00008233 } else {
8234 samplingRates = devDesc->getAudioProfiles().getSampleRatesFor(format);
François Gaffie112b0af2015-11-19 16:13:25 +01008235 }
8236 }
8237 if (profiles.hasDynamicChannelsFor(format)) {
8238 reply = mpClientInterface->getParameters(ioHandle,
8239 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07008240 AudioParameter::keyStreamSupportedChannels);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008241 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.c_str());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008242 AudioParameter repliedParameters(reply);
8243 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008244 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008245 channelMasks = channelMasksFromString(reply.c_str());
jiabinf26596b2023-04-12 18:56:39 +00008246 } else {
8247 channelMasks = devDesc->getAudioProfiles().getChannelMasksFor(format);
8248 }
8249 if (channelMasks.has_value() && (device == AUDIO_DEVICE_OUT_HDMI
8250 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD))) {
8251 modifySurroundChannelMasks(&channelMasks.value());
François Gaffie112b0af2015-11-19 16:13:25 +01008252 }
8253 }
jiabin3e277cc2019-09-10 14:27:34 -07008254 addDynamicAudioProfileAndSort(
jiabinf26596b2023-04-12 18:56:39 +00008255 profiles, new AudioProfile(
8256 format, channelMasks.value_or(ChannelMaskSet()), samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01008257 }
8258}
Eric Laurentd60560a2015-04-10 11:31:20 -07008259
Mikhail Naganovdc769682018-05-04 15:34:08 -07008260status_t AudioPolicyManager::installPatch(const char *caller,
8261 audio_patch_handle_t *patchHandle,
8262 AudioIODescriptorInterface *ioDescriptor,
8263 const struct audio_patch *patch,
8264 int delayMs)
8265{
8266 ssize_t index = mAudioPatches.indexOfKey(
8267 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8268 *patchHandle : ioDescriptor->getPatchHandle());
8269 sp<AudioPatch> patchDesc;
8270 status_t status = installPatch(
8271 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8272 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008273 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008274 }
8275 return status;
8276}
8277
8278status_t AudioPolicyManager::installPatch(const char *caller,
8279 ssize_t index,
8280 audio_patch_handle_t *patchHandle,
8281 const struct audio_patch *patch,
8282 int delayMs,
8283 uid_t uid,
8284 sp<AudioPatch> *patchDescPtr)
8285{
8286 sp<AudioPatch> patchDesc;
8287 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8288 if (index >= 0) {
8289 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008290 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008291 }
8292
8293 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8294 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8295 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8296 if (status == NO_ERROR) {
8297 if (index < 0) {
8298 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008299 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008300 } else {
8301 patchDesc->mPatch = *patch;
8302 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008303 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008304 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008305 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008306 }
8307 nextAudioPortGeneration();
8308 mpClientInterface->onAudioPatchListUpdate();
8309 }
8310 if (patchDescPtr) *patchDescPtr = patchDesc;
8311 return status;
8312}
8313
jiabinbce0c1d2020-10-05 11:20:18 -07008314bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8315{
8316 const TrackClientVector activeClients = output->getActiveClients();
8317 if (activeClients.empty()) {
8318 return true;
8319 }
8320 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8321 if (index < 0) {
8322 ALOGE("%s, no audio patch found while there are active clients on output %d",
8323 __func__, output->getId());
8324 return false;
8325 }
8326 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8327 DeviceVector routedDevices;
8328 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8329 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8330 patchDesc->mPatch.sinks[i].id);
8331 if (device == nullptr) {
8332 ALOGE("%s, no audio device found with id(%d)",
8333 __func__, patchDesc->mPatch.sinks[i].id);
8334 return false;
8335 }
8336 routedDevices.add(device);
8337 }
8338 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008339 if (client->isInvalid()) {
8340 // No need to take care about invalidated clients.
8341 continue;
8342 }
jiabinbce0c1d2020-10-05 11:20:18 -07008343 sp<DeviceDescriptor> preferredDevice =
8344 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8345 if (mEngine->getOutputDevicesForAttributes(
8346 client->attributes(), preferredDevice, false) == routedDevices) {
8347 return false;
8348 }
8349 }
8350 return true;
8351}
8352
8353sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008354 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008355 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8356 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008357{
8358 for (const auto& device : devices) {
8359 // TODO: This should be checking if the profile supports the device combo.
8360 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008361 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8362 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008363 return nullptr;
8364 }
8365 }
8366 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8367 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008368 status_t status = desc->open(halConfig, mixerConfig, devices,
8369 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008370 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008371 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008372 return nullptr;
8373 }
8374
8375 // Here is where the out_set_parameters() for card & device gets called
8376 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8377 const audio_devices_t deviceType = device->type();
8378 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008379 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008380 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8381 mpClientInterface->setParameters(output, String8(param));
8382 free(param);
8383 }
8384 updateAudioProfiles(device, output, profile->getAudioProfiles());
8385 if (!profile->hasValidAudioProfile()) {
8386 ALOGW("%s() missing param", __func__);
8387 desc->close();
8388 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008389 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8390 // Reopen the output with the best audio profile picked by APM when the profile supports
8391 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008392 desc->close();
8393 output = AUDIO_IO_HANDLE_NONE;
8394 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8395 profile->pickAudioProfile(
8396 config.sample_rate, config.channel_mask, config.format);
8397 config.offload_info.sample_rate = config.sample_rate;
8398 config.offload_info.channel_mask = config.channel_mask;
8399 config.offload_info.format = config.format;
8400
jiabina84c3d32022-12-02 18:59:55 +00008401 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008402 if (status != NO_ERROR) {
8403 return nullptr;
8404 }
8405 }
8406
8407 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008408
baek.kim -61c20122022-07-27 10:05:32 +00008409 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8410 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8411
jiabinbce0c1d2020-10-05 11:20:18 -07008412 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8413 sp<AudioPolicyMix> policyMix;
8414 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8415 policyMix->setOutput(desc);
8416 desc->mPolicyMix = policyMix;
8417 } else {
8418 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008419 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008420 }
8421
baek.kim -61c20122022-07-27 10:05:32 +00008422 } else if (hasPrimaryOutput() && speaker != nullptr
8423 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008424 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8425 // no duplicated output for:
8426 // - direct outputs
8427 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008428 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008429 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8430
8431 //TODO: configure audio effect output stage here
8432
8433 // open a duplicating output thread for the new output and the primary output
8434 sp<SwAudioOutputDescriptor> dupOutputDesc =
8435 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8436 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8437 if (status == NO_ERROR) {
8438 // add duplicated output descriptor
8439 addOutput(duplicatedOutput, dupOutputDesc);
8440 } else {
8441 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8442 mPrimaryOutput->mIoHandle, output);
8443 desc->close();
8444 removeOutput(output);
8445 nextAudioPortGeneration();
8446 return nullptr;
8447 }
8448 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008449 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8450 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8451 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008452 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008453 }
jiabinbce0c1d2020-10-05 11:20:18 -07008454 return desc;
8455}
8456
jiabinf1c73972022-04-14 16:28:52 -07008457status_t AudioPolicyManager::getDevicesForAttributes(
8458 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8459 // Devices are determined in the following precedence:
8460 //
8461 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8462 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8463 //
8464 // If no such dynamic policy then
8465 // 2) Devices containing an active client using setPreferredDevice
8466 // with same strategy as the attributes.
8467 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8468 //
8469 // If no corresponding active client with setPreferredDevice then
8470 // 3) Devices associated with the strategy determined by the attributes
8471 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8472 //
8473 // See related getOutputForAttrInt().
8474
8475 // check dynamic policies but only for primary descriptors (secondary not used for audible
8476 // audio routing, only used for duplication for playback capture)
8477 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008478 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008479 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008480 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8481 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8482 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008483 if (status != OK) {
8484 return status;
8485 }
8486
8487 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8488 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8489 // as they are unaffected by device/stream volume
8490 // (per SwAudioOutputDescriptor::isFixedVolume()).
8491 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8492 ) {
8493 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8494 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8495 devices.add(deviceDesc);
8496 } else {
8497 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8498 // which selects setPreferredDevice if active. This means forVolume call
8499 // will take an active setPreferredDevice, if such exists.
8500
8501 devices = mEngine->getOutputDevicesForAttributes(
8502 attr, nullptr /* preferredDevice */, false /* fromCache */);
8503 }
8504
8505 if (forVolume) {
8506 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8507 // for single volume control in AudioService (such relationship should exist if
8508 // SPEAKER_SAFE is present).
8509 //
8510 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8511 DeviceVector speakerSafeDevices =
8512 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8513 if (!speakerSafeDevices.isEmpty()) {
8514 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8515 devices.remove(speakerSafeDevices);
8516 }
8517 }
8518
8519 return NO_ERROR;
8520}
8521
8522status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8523 AudioProfileVector& audioProfiles,
8524 uint32_t flags,
8525 bool isInput) {
8526 for (const auto& hwModule : mHwModules) {
8527 // the MSD module checks for different conditions
8528 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8529 continue;
8530 }
8531 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8532 : hwModule->getOutputProfiles();
8533 for (const auto& profile : ioProfiles) {
8534 if (!profile->areAllDevicesSupported(devices) ||
8535 !profile->isCompatibleProfileForFlags(
8536 flags, false /*exactMatchRequiredForInputFlags*/)) {
8537 continue;
8538 }
8539 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8540 }
8541 }
8542
8543 if (!isInput) {
8544 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8545 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8546 if (msdModule != nullptr) {
8547 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8548 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8549 for (const auto &profile: msdModule->getOutputProfiles()) {
8550 if (!profile->asAudioPort()->isDirectOutput()) {
8551 continue;
8552 }
8553 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8554 }
8555 } else {
8556 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8557 }
8558 }
8559 }
8560
8561 return NO_ERROR;
8562}
8563
jiabin3ff8d7d2022-12-13 06:27:44 +00008564sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8565 const audio_config_t *config,
8566 audio_output_flags_t flags,
8567 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008568 closeOutput(outputDesc->mIoHandle);
8569 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8570 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8571 if (preferredOutput == nullptr) {
8572 ALOGE("%s failed to reopen output device=%d, caller=%s",
8573 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008574 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008575 return preferredOutput;
8576}
8577
8578void AudioPolicyManager::reopenOutputsWithDevices(
8579 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8580 for (const auto& [output, devices] : outputsToReopen) {
8581 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8582 closeOutput(output);
8583 openOutputWithProfileAndDevice(desc->mProfile, devices);
8584 }
jiabina84c3d32022-12-02 18:59:55 +00008585}
8586
jiabinc44b3462022-12-08 12:52:31 -08008587PortHandleVector AudioPolicyManager::getClientsForStream(
8588 audio_stream_type_t streamType) const {
8589 PortHandleVector clients;
8590 for (size_t i = 0; i < mOutputs.size(); ++i) {
8591 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8592 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8593 }
8594 return clients;
8595}
8596
8597void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8598 PortHandleVector clients;
8599 for (auto stream : streams) {
8600 PortHandleVector clientsForStream = getClientsForStream(stream);
8601 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8602 }
8603 mpClientInterface->invalidateTracks(clients);
8604}
8605
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008606} // namespace android