blob: 7e112040082b27d5e88290d70a221969cd39b340 [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{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800514 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
515 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800516
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800517 // connect/disconnect only 1 device at a time
518 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
519
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700521 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800522 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800523 // Nothing to do: device is not connected
524 return NO_ERROR;
525 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800526 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800527
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700528 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800529 // configure codecs.
530 // Handle two specific cases by sending a set parameter to
531 // configure A2DP codecs. No need to toggle device state.
532 // Case 1: A2DP active device switches from primary to primary
533 // module
534 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100535 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700536 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800537 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
538 if (availablePrimaryOutputDevices().contains(devDesc) &&
539 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100540 bool isA2dp = audio_is_a2dp_out_device(device);
541 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
542 : String8(AudioParameter::keyReconfigLeSupported);
543 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800544 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100545 int isReconfigSupported;
546 repliedParameters.getInt(supportKey, isReconfigSupported);
547 if (isReconfigSupported) {
548 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
549 : String8(AudioParameter::keyReconfigLe);
550 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800551 param.add(key, String8("true"));
552 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
553 devDesc->setEncodedFormat(encodedFormat);
554 return NO_ERROR;
555 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700556 }
557 }
cnx421bd2dcc42020-07-11 14:58:44 +0800558 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
559 for (size_t i = 0; i < mOutputs.size(); i++) {
560 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
561 // mute media strategies and delay device switch by the largest
562 // This avoid sending the music tail into the earpiece or headset.
563 setStrategyMute(musicStrategy, true, desc);
564 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
565 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
566 nullptr, true /*fromCache*/).types());
567 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800568 // Toggle the device state: UNAVAILABLE -> AVAILABLE
569 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100570 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800571 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800572 device_address, device_name,
573 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800574 if (status != NO_ERROR) {
575 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
576 status);
577 return status;
578 }
579
580 status = setDeviceConnectionState(device,
581 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800582 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800583 if (status != NO_ERROR) {
584 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
585 status);
586 return status;
587 }
588
589 return NO_ERROR;
590}
591
Pattydd807582021-11-04 21:01:03 +0800592status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
593 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800594{
Pattydd807582021-11-04 21:01:03 +0800595 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800596 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800597 std::unordered_set<audio_format_t> formatSet;
598 sp<HwModule> primaryModule =
599 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700600 if (primaryModule == nullptr) {
601 ALOGE("%s() unable to get primary module", __func__);
602 return NO_INIT;
603 }
Pattydd807582021-11-04 21:01:03 +0800604
605 DeviceTypeSet audioDeviceSet;
606
607 switch(device) {
608 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
609 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
610 break;
611 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800612 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
613 break;
614 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
615 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800616 break;
617 default:
618 ALOGE("%s() device type 0x%08x not supported", __func__, device);
619 return BAD_VALUE;
620 }
621
jiabin9a3361e2019-10-01 09:38:30 -0700622 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800623 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800624 for (const auto& device : declaredDevices) {
625 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800626 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800627 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800628 return status;
629}
630
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100631DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
632{
633 DeviceVector rxSinkdevices{};
634 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
635 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
636 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
637 auto rxSinkDevice = rxSinkdevices.itemAt(0);
638 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
639 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
640 // retrieve Rx Source device descriptor
641 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
642 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
643
644 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
645 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
646 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
647 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
648 return DeviceVector(rxSinkDevice);
649 }
650 }
651 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
652 // the device returned is not necessarily reachable via this output
653 // (filter later by setOutputDevices())
654 return getNewOutputDevices(mPrimaryOutput, fromCache);
655}
656
657status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
658{
François Gaffiedb1755b2023-09-01 11:50:35 +0200659 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100660 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
661 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
662 }
663 return INVALID_OPERATION;
664}
665
666status_t AudioPolicyManager::updateCallRoutingInternal(
667 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700668{
669 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100670 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700671 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200672 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700673 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100674 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700675 }
François Gaffie11d30102018-11-02 16:09:09 +0100676
Francois Gaffie716e1432019-01-14 16:58:59 +0100677 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100678 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200679
680 disconnectTelephonyAudioSource(mCallRxSourceClient);
681 disconnectTelephonyAudioSource(mCallTxSourceClient);
682
683 if (rxDevices.isEmpty()) {
684 ALOGW("%s() no selected output device", __func__);
685 return INVALID_OPERATION;
686 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000687 if (txSourceDevice == nullptr) {
688 ALOGE("%s() selected input device not available", __func__);
689 return INVALID_OPERATION;
690 }
François Gaffiec005e562018-11-06 15:04:49 +0100691
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100692 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100693 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700694
François Gaffie9eb18552018-11-05 10:33:26 +0100695 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700696 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100697 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700698 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100699 // retrieve Rx Source and Tx Sink device descriptors
700 sp<DeviceDescriptor> rxSourceDevice =
701 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
702 String8(),
703 AUDIO_FORMAT_DEFAULT);
704 sp<DeviceDescriptor> txSinkDevice =
705 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
706 String8(),
707 AUDIO_FORMAT_DEFAULT);
708
709 // RX and TX Telephony device are declared by Primary Audio HAL
710 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
711 (telephonyRxModule->getHalVersionMajor() >= 3)) {
712 if (rxSourceDevice == 0 || txSinkDevice == 0) {
713 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100714 ALOGE("%s() no telephony Tx and/or RX device", __func__);
715 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100716 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100717 // createAudioPatchInternal now supports both HW / SW bridging
718 createRxPatch = true;
719 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100720 } else {
721 // If the RX device is on the primary HW module, then use legacy routing method for
722 // voice calls via setOutputDevice() on primary output.
723 // Otherwise, create two audio patches for TX and RX path.
724 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
725 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700726 // If the TX device is also on the primary HW module, setOutputDevice() will take care
727 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100728 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
729 (txSinkDevice != 0);
730 }
731 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
732 // Otherwise, create two audio patches for TX and RX path.
733 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200734 if (!hasPrimaryOutput()) {
735 ALOGW("%s() no primary output available", __func__);
736 return INVALID_OPERATION;
737 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530738 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700739 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200740 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800741 // If the TX device is on the primary HW module but RX device is
742 // on other HW module, SinkMetaData of telephony input should handle it
743 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700744 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700745 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100746 // terminate active capture if on the same HW module as the call TX source device
747 // FIXME: would be better to refine to only inputs whose profile connects to the
748 // call TX device but this information is not in the audio patch and logic here must be
749 // symmetric to the one in startInput()
750 for (const auto& activeDesc : mInputs.getActiveInputs()) {
751 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
752 closeActiveClients(activeDesc);
753 }
754 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200755 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800756 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100757 if (waitMs != nullptr) {
758 *waitMs = muteWaitMs;
759 }
760 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800761}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700762
Mikhail Naganov100f0122018-11-29 11:22:16 -0800763bool AudioPolicyManager::isDeviceOfModule(
764 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
765 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
766 if (module != 0) {
767 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
768 .indexOf(devDesc) != NAME_NOT_FOUND
769 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
770 .indexOf(devDesc) != NAME_NOT_FOUND;
771 }
772 return false;
773}
774
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200775void AudioPolicyManager::connectTelephonyRxAudioSource()
776{
Francois Gaffie601801d2021-06-22 13:27:39 +0200777 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200778 const struct audio_port_config source = {
779 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
780 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
781 };
782 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200783 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
784 ALOGE_IF(mCallRxSourceClient == nullptr,
785 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200786}
787
Francois Gaffie601801d2021-06-22 13:27:39 +0200788void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200789{
Francois Gaffie601801d2021-06-22 13:27:39 +0200790 if (clientDesc == nullptr) {
791 return;
792 }
793 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
794 "%s error stopping audio source", __func__);
795 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200796}
797
798void AudioPolicyManager::connectTelephonyTxAudioSource(
799 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
800 uint32_t delayMs)
801{
Francois Gaffie601801d2021-06-22 13:27:39 +0200802 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200803 if (srcDevice == nullptr || sinkDevice == nullptr) {
804 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
805 return;
806 }
807 PatchBuilder patchBuilder;
808 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
809 ALOGV("%s between source %s and sink %s", __func__,
810 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200811 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200812 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
813
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200814 struct audio_port_config source = {};
815 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200816 mCallTxSourceClient = new InternalSourceClientDescriptor(
817 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200818 mCommunnicationStrategy, toVolumeSource(aa));
819 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
820 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200821 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
822 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200823 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
824 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200825 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200826 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200827}
828
Eric Laurente0720872014-03-11 09:30:41 -0700829void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700830{
831 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100832 // store previous phone state for management of sonification strategy below
833 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100834 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100835
836 if (mEngine->setPhoneState(state) != NO_ERROR) {
837 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700838 return;
839 }
François Gaffie2110e042015-03-24 08:41:51 +0100840 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700841 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700842 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700843 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800844 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700845 }
846
François Gaffie2110e042015-03-24 08:41:51 +0100847 /**
848 * Switching to or from incall state or switching between telephony and VoIP lead to force
849 * routing command.
850 */
Eric Laurent74b71512019-11-06 17:21:57 -0800851 bool force = ((isStateInCall(oldState) != isStateInCall(state))
852 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700853
854 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700855 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700856
Eric Laurente552edb2014-03-10 17:42:56 -0700857 int delayMs = 0;
858 if (isStateInCall(state)) {
859 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100860 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
861 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700862 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700863 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700864 // mute media and sonification strategies and delay device switch by the largest
865 // latency of any output where either strategy is active.
866 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100867 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
868 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
869 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700870 (delayMs < (int)desc->latency()*2)) {
871 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700872 }
François Gaffiec005e562018-11-06 15:04:49 +0100873 setStrategyMute(musicStrategy, true, desc);
874 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
875 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
876 nullptr, true /*fromCache*/).types());
877 setStrategyMute(sonificationStrategy, true, desc);
878 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
879 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
880 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700881 }
882 }
883
François Gaffiedb1755b2023-09-01 11:50:35 +0200884 if (state == AUDIO_MODE_IN_CALL) {
885 (void)updateCallRouting(false /*fromCache*/, delayMs);
886 } else {
887 if (oldState == AUDIO_MODE_IN_CALL) {
888 disconnectTelephonyAudioSource(mCallRxSourceClient);
889 disconnectTelephonyAudioSource(mCallTxSourceClient);
890 }
891 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100892 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
893 // force routing command to audio hardware when ending call
894 // even if no device change is needed
895 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
896 rxDevices = mPrimaryOutput->devices();
897 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530898 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700899 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700900 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700901
jiabin3ff8d7d2022-12-13 06:27:44 +0000902 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700903 // reevaluate routing on all outputs in case tracks have been started during the call
904 for (size_t i = 0; i < mOutputs.size(); i++) {
905 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100906 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200907 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
908 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000909 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
910 // If the device is using preferred mixer attributes, the output need to reopen
911 // with default configuration when the new selected devices are different from
912 // current routing devices.
913 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
914 continue;
915 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530916 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200917 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700918 }
919 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000920 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700921
Eric Laurent96d1dda2022-03-14 17:14:19 +0100922 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
923
Eric Laurente552edb2014-03-10 17:42:56 -0700924 if (isStateInCall(state)) {
925 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700926 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800927 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700928 }
929
930 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100931 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
932 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700933}
934
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700935audio_mode_t AudioPolicyManager::getPhoneState() {
936 return mEngine->getPhoneState();
937}
938
Eric Laurente0720872014-03-11 09:30:41 -0700939void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100940 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700941{
François Gaffie2110e042015-03-24 08:41:51 +0100942 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700943 if (config == mEngine->getForceUse(usage)) {
944 return;
945 }
Eric Laurente552edb2014-03-10 17:42:56 -0700946
François Gaffie2110e042015-03-24 08:41:51 +0100947 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
948 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
949 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700950 }
François Gaffie2110e042015-03-24 08:41:51 +0100951 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
952 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
953 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700954
955 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700956 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800957
Eric Laurent22fcda22019-05-17 16:28:47 -0700958 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
959 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800960 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700961 }
962
Eric Laurentdc462862016-07-19 12:29:53 -0700963 //FIXME: workaround for truncated touch sounds
964 // to be removed when the problem is handled by system UI
965 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700966 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
967 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
968 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700969
970 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100971 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700972}
973
Eric Laurente0720872014-03-11 09:30:41 -0700974void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700975{
976 ALOGV("setSystemProperty() property %s, value %s", property, value);
977}
978
Dorin Drimusecc9f422022-03-09 17:57:40 +0100979// Find an MSD output profile compatible with the parameters passed.
980// When "directOnly" is set, restrict search to profiles for direct outputs.
981sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
982 const DeviceVector& devices,
983 uint32_t samplingRate,
984 audio_format_t format,
985 audio_channel_mask_t channelMask,
986 audio_output_flags_t flags,
987 bool directOnly)
988{
989 flags = getRelevantFlags(flags, directOnly);
990
991 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
992 if (msdModule != nullptr) {
993 // for the msd module check if there are patches to the output devices
994 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
995 HwModuleCollection modules;
996 modules.add(msdModule);
997 return searchCompatibleProfileHwModules(
998 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
999 flags, directOnly);
1000 }
1001 }
1002 return nullptr;
1003}
1004
Michael Chana94fbb22018-04-24 14:31:19 +10001005// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1006// search to profiles for direct outputs.
1007sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001008 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001009 uint32_t samplingRate,
1010 audio_format_t format,
1011 audio_channel_mask_t channelMask,
1012 audio_output_flags_t flags,
1013 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001014{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001015 flags = getRelevantFlags(flags, directOnly);
1016
1017 return searchCompatibleProfileHwModules(
1018 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1019}
1020
1021audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1022 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001023 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001024 // only retain flags that will drive the direct output profile selection
1025 // if explicitly requested
1026 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001027 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001028 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1029 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001030 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001031 return flags;
1032}
Eric Laurent861a6282015-05-18 15:40:16 -07001033
Dorin Drimusecc9f422022-03-09 17:57:40 +01001034sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1035 const HwModuleCollection& hwModules,
1036 const DeviceVector& devices,
1037 uint32_t samplingRate,
1038 audio_format_t format,
1039 audio_channel_mask_t channelMask,
1040 audio_output_flags_t flags,
1041 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001042 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001043 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001044 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001045 if (!curProfile->isCompatibleProfile(devices,
1046 samplingRate, NULL /*updatedSamplingRate*/,
1047 format, NULL /*updatedFormat*/,
1048 channelMask, NULL /*updatedChannelMask*/,
1049 flags)) {
1050 continue;
1051 }
1052 // reject profiles not corresponding to a device currently available
1053 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1054 continue;
1055 }
1056 // reject profiles if connected device does not support codec
1057 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1058 continue;
1059 }
1060 if (!directOnly) {
1061 return curProfile;
1062 }
1063
1064 // when searching for direct outputs, if several profiles are compatible, give priority
1065 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001066 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001067 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001068 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001069 }
1070 profile = curProfile;
1071 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1072 break;
1073 }
Eric Laurente552edb2014-03-10 17:42:56 -07001074 }
1075 }
Eric Laurent861a6282015-05-18 15:40:16 -07001076 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001077}
1078
Eric Laurentfa0f6742021-08-17 18:39:44 +02001079sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001080 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001081{
1082 for (const auto& hwModule : mHwModules) {
1083 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001084 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001085 continue;
1086 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001087 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001088 // reject profiles not corresponding to a device currently available
1089 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1090 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1091 continue;
1092 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001093 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1094 != devices.size()) {
1095 continue;
1096 }
1097 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001098 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1099 return curProfile;
1100 }
1101 }
1102 return nullptr;
1103}
1104
Eric Laurentf4e63452017-11-06 19:31:46 +00001105audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001106{
François Gaffiec005e562018-11-06 15:04:49 +01001107 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001108
1109 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1110 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1111 // format, flags, etc. This may result in some discrepancy for functions that utilize
1112 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1113 // and AudioSystem::getOutputSamplingRate().
1114
François Gaffie11d30102018-11-02 16:09:09 +01001115 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001116 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1117 if (stream == AUDIO_STREAM_MUSIC &&
1118 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1119 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1120 }
1121 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001122
François Gaffie11d30102018-11-02 16:09:09 +01001123 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1124 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001125 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001126}
1127
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001128status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1129 const audio_attributes_t *srcAttr,
1130 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001131{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001132 if (srcAttr != NULL) {
1133 if (!isValidAttributes(srcAttr)) {
1134 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1135 __func__,
1136 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1137 srcAttr->tags);
1138 return BAD_VALUE;
1139 }
1140 *dstAttr = *srcAttr;
1141 } else {
1142 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1143 ALOGE("%s: invalid stream type", __func__);
1144 return BAD_VALUE;
1145 }
François Gaffiec005e562018-11-06 15:04:49 +01001146 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001147 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001148
1149 // Only honor audibility enforced when required. The client will be
1150 // forced to reconnect if the forced usage changes.
1151 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001152 dstAttr->flags = static_cast<audio_flags_mask_t>(
1153 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001154 }
1155
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001156 return NO_ERROR;
1157}
1158
Kevin Rocard153f92d2018-12-18 18:33:28 -08001159status_t AudioPolicyManager::getOutputForAttrInt(
1160 audio_attributes_t *resultAttr,
1161 audio_io_handle_t *output,
1162 audio_session_t session,
1163 const audio_attributes_t *attr,
1164 audio_stream_type_t *stream,
1165 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001166 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001167 audio_output_flags_t *flags,
1168 audio_port_handle_t *selectedDeviceId,
1169 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001170 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001171 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001172 bool *isSpatialized,
1173 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001174{
François Gaffiec005e562018-11-06 15:04:49 +01001175 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001176 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001177 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001178 const sp<DeviceDescriptor> requestedDevice =
1179 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1180
Eric Laurent8a1095a2019-11-08 14:44:16 -08001181 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001182 *isSpatialized = false;
1183
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001184 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1185 if (status != NO_ERROR) {
1186 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001187 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001188 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001189 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001190 }
François Gaffiec005e562018-11-06 15:04:49 +01001191 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001192
François Gaffiec005e562018-11-06 15:04:49 +01001193 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1194 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001195
Oscar Azucena873d10f2023-01-12 18:34:42 -08001196 bool usePrimaryOutputFromPolicyMixes = false;
1197
Kevin Rocard153f92d2018-12-18 18:33:28 -08001198 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1199 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1200 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001201 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001202 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1203 .channel_mask = config->channel_mask,
1204 .format = config->format,
1205 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001206 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001207 mAvailableOutputDevices, requestedDevice, primaryMix,
1208 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001209 if (status != OK) {
1210 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001211 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001212
Kevin Rocard153f92d2018-12-18 18:33:28 -08001213 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001214 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1215 && !audio_is_linear_pcm(config->format)) {
1216 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001217 return BAD_VALUE;
1218 }
1219 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001220 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001221 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1222 primaryMix->mDeviceAddress,
1223 AUDIO_FORMAT_DEFAULT);
1224 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001225 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001226 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1227 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001228 // if a direct output can be opened to deliver the track's multi-channel content to the
1229 // output rather than being downmixed by the primary output, then use this direct
1230 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1231 // mix.
1232 bool tryDirectForChannelMask = policyDesc != nullptr
1233 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1234 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001235 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001236 audio_io_handle_t newOutput;
1237 status = openDirectOutput(
1238 *stream, session, config,
1239 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001240 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001241 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001242 policyDesc = mOutputs.valueFor(newOutput);
1243 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001244 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001245 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001246 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;
jiabin24ff57a2023-11-27 21:06:51 +00001252 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1253 : AUDIO_PORT_HANDLE_NONE;
1254 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1255 // Remove direct flag as it is not on a direct output.
1256 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1257 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001258
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001259 ALOGV("getOutputForAttr() returns output %d", *output);
1260 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1261 *outputType = API_OUT_MIX_PLAYBACK;
1262 } else {
1263 *outputType = API_OUTPUT_LEGACY;
1264 }
1265 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001266 } else {
1267 if (policyMixDevice != nullptr) {
1268 ALOGE("%s, try to use primary mix but no output found", __func__);
1269 return INVALID_OPERATION;
1270 }
1271 // Fallback to default engine selection as the selected primary mix device is not
1272 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001273 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001274 }
François Gaffiec005e562018-11-06 15:04:49 +01001275 // Virtual sources must always be dynamicaly or explicitly routed
1276 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1277 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1278 return BAD_VALUE;
1279 }
1280 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1281 // in order to let the choice of the order to future vendor engine
1282 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001283
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001284 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001285 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001286 }
1287
Nadav Barb2f18162018-07-18 13:01:53 +03001288 // Set incall music only if device was explicitly set, and fallback to the device which is
1289 // chosen by the engine if not.
1290 // FIXME: provide a more generic approach which is not device specific and move this back
1291 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001292 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001293 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001294 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001295 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001296 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001297 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001298 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001299 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001300 }
1301 }
1302
François Gaffiec005e562018-11-06 15:04:49 +01001303 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1304 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1305 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001306
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001307 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001308 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001309 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001310 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001311 ALOGV("%s() Using MSD devices %s instead of devices %s",
1312 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001313 } else {
1314 *output = AUDIO_IO_HANDLE_NONE;
1315 }
1316 }
1317 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001318 sp<PreferredMixerAttributesInfo> info = nullptr;
1319 if (outputDevices.size() == 1) {
1320 info = getPreferredMixerAttributesInfo(
1321 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001322 mEngine->getProductStrategyForAttributes(*resultAttr),
1323 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001324 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1325 // and it is currently active.
1326 if (info != nullptr && info->getUid() != uid &&
1327 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1328 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001329 info = nullptr;
1330 }
1331 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001332 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001333 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001334 // The client will be active if the client is currently preferred mixer owner and the
1335 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001336 *isBitPerfect = (info != nullptr
1337 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001338 && info->getUid() == uid
1339 && *output != AUDIO_IO_HANDLE_NONE
1340 // When bit-perfect output is selected for the preferred mixer attributes owner,
1341 // only need to consider the config matches.
1342 && mOutputs.valueFor(*output)->isConfigurationMatched(
1343 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001344 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001345 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001346 AudioProfileVector profiles;
1347 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1348 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001349 const auto channels = profiles[0]->getChannels();
1350 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1351 config->channel_mask = *channels.begin();
1352 }
1353 const auto sampleRates = profiles[0]->getSampleRates();
1354 if (!sampleRates.empty() &&
1355 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1356 config->sample_rate = *sampleRates.begin();
1357 }
jiabinf1c73972022-04-14 16:28:52 -07001358 config->format = profiles[0]->getFormat();
1359 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001360 return INVALID_OPERATION;
1361 }
Paul McLeanaa981192015-03-21 09:55:15 -07001362
François Gaffiec005e562018-11-06 15:04:49 +01001363 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001364 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001365 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001366 *selectedDeviceId = outputDevice->getId();
1367 break;
1368 }
1369 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001370
Eric Laurent8a1095a2019-11-08 14:44:16 -08001371 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1372 *outputType = API_OUTPUT_TELEPHONY_TX;
1373 } else {
1374 *outputType = API_OUTPUT_LEGACY;
1375 }
1376
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001377 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1378
1379 return NO_ERROR;
1380}
1381
1382status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1383 audio_io_handle_t *output,
1384 audio_session_t session,
1385 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001386 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001387 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001388 audio_output_flags_t *flags,
1389 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001390 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001391 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001392 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001393 bool *isSpatialized,
1394 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001395{
1396 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1397 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1398 return INVALID_OPERATION;
1399 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001400 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001401 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001402 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001403 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001404 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001405 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001406 const sp<DeviceDescriptor> requestedDevice =
1407 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1408
1409 // Prevent from storing invalid requested device id in clients
1410 const audio_port_handle_t sanitizedRequestedPortId =
1411 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1412 *selectedDeviceId = sanitizedRequestedPortId;
1413
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001414 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001415 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001416 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1417 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001418 if (status != NO_ERROR) {
1419 return status;
1420 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001421 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001422 if (secondaryOutputs != nullptr) {
1423 for (auto &secondaryMix : secondaryMixes) {
1424 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1425 if (outputDesc != nullptr &&
1426 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1427 secondaryOutputs->push_back(outputDesc->mIoHandle);
1428 weakSecondaryOutputDescs.push_back(outputDesc);
1429 }
1430 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001431 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001432
Eric Laurent8fc147b2018-07-22 19:13:55 -07001433 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001434 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001435 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001436 };
jiabin4ef93452019-09-10 14:29:54 -07001437 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001438
Eric Laurentc209fe42020-06-05 18:11:23 -07001439 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001440 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001441 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001442 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001443 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001444 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001445 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001446 std::move(weakSecondaryOutputDescs),
1447 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001448 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001449
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001450 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1451 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001452
Eric Laurente83b55d2014-11-14 10:06:21 -08001453 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001454}
1455
Eric Laurentc529cf62020-04-17 18:19:10 -07001456status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1457 audio_session_t session,
1458 const audio_config_t *config,
1459 audio_output_flags_t flags,
1460 const DeviceVector &devices,
1461 audio_io_handle_t *output) {
1462
1463 *output = AUDIO_IO_HANDLE_NONE;
1464
1465 // skip direct output selection if the request can obviously be attached to a mixed output
1466 // and not explicitly requested
1467 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1468 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1469 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1470 return NAME_NOT_FOUND;
1471 }
1472
1473 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1474 // This prevents creating an offloaded track and tearing it down immediately after start
1475 // when audioflinger detects there is an active non offloadable effect.
1476 // FIXME: We should check the audio session here but we do not have it in this context.
1477 // This may prevent offloading in rare situations where effects are left active by apps
1478 // in the background.
1479 sp<IOProfile> profile;
1480 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1481 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1482 profile = getProfileForOutput(
1483 devices, config->sample_rate, config->format, config->channel_mask,
1484 flags, true /* directOnly */);
1485 }
1486
1487 if (profile == nullptr) {
1488 return NAME_NOT_FOUND;
1489 }
1490
1491 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1492 for (size_t i = 0; i < mOutputs.size(); i++) {
1493 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1494 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1495 // reuse direct output if currently open by the same client
1496 // and configured with same parameters
1497 if ((config->sample_rate == desc->getSamplingRate()) &&
1498 (config->format == desc->getFormat()) &&
1499 (config->channel_mask == desc->getChannelMask()) &&
1500 (session == desc->mDirectClientSession)) {
1501 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001502 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001503 mOutputs.keyAt(i), session);
1504 *output = mOutputs.keyAt(i);
1505 return NO_ERROR;
1506 }
1507 }
1508 }
1509
1510 if (!profile->canOpenNewIo()) {
1511 return NAME_NOT_FOUND;
1512 }
1513
1514 sp<SwAudioOutputDescriptor> outputDesc =
1515 new SwAudioOutputDescriptor(profile, mpClientInterface);
1516
Michael Chan6fb34492020-12-08 15:44:49 +11001517 // An MSD patch may be using the only output stream that can service this request. Release
1518 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001519 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001520
Eric Laurentf1f22e72021-07-13 14:04:14 +02001521 status_t status =
1522 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001523
1524 // only accept an output with the requested parameters
1525 if (status != NO_ERROR ||
1526 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1527 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1528 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1529 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1530 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1531 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1532 config->channel_mask, outputDesc->getChannelMask());
1533 if (*output != AUDIO_IO_HANDLE_NONE) {
1534 outputDesc->close();
1535 }
1536 // fall back to mixer output if possible when the direct output could not be open
1537 if (audio_is_linear_pcm(config->format) &&
1538 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1539 return NAME_NOT_FOUND;
1540 }
1541 *output = AUDIO_IO_HANDLE_NONE;
1542 return BAD_VALUE;
1543 }
1544 outputDesc->mDirectOpenCount = 1;
1545 outputDesc->mDirectClientSession = session;
1546
1547 addOutput(*output, outputDesc);
1548 mPreviousOutputs = mOutputs;
1549 ALOGV("%s returns new direct output %d", __func__, *output);
1550 mpClientInterface->onAudioPortListUpdate();
1551 return NO_ERROR;
1552}
1553
François Gaffie11d30102018-11-02 16:09:09 +01001554audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1555 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001556 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001557 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001558 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001559 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001560 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001561 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001562 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001563{
Andy Hungc88b0642018-04-27 15:42:35 -07001564 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001565
jiabine375d412019-02-26 12:54:53 -08001566 // Discard haptic channel mask when forcing muting haptic channels.
1567 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001568 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1569 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001570
Eric Laurente552edb2014-03-10 17:42:56 -07001571 // open a direct output if required by specified parameters
1572 //force direct flag if offload flag is set: offloading implies a direct output stream
1573 // and all common behaviors are driven by checking only the direct flag
1574 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001575 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1576 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001577 }
Nadav Bar766fb022018-01-07 12:18:03 +02001578 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1579 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001580 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001581
1582 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1583
Eric Laurente83b55d2014-11-14 10:06:21 -08001584 // only allow deep buffering for music stream type
1585 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001586 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001587 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001588 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001589 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1590 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001591 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001592 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001593 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001594 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001595 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001596 audio_is_linear_pcm(config->format) &&
1597 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001598 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001599 AUDIO_OUTPUT_FLAG_DIRECT);
1600 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001601 }
Eric Laurente552edb2014-03-10 17:42:56 -07001602
Carter Hsua3abb402021-10-26 11:11:20 +08001603 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1604 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1605 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1606 }
1607
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001608 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001609 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001610 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001611 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001612 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001613 }
1614
Eric Laurentc529cf62020-04-17 18:19:10 -07001615 audio_config_t directConfig = *config;
1616 directConfig.channel_mask = channelMask;
1617 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1618 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001619 return output;
1620 }
1621
Eric Laurent14cbfca2016-03-17 09:42:16 -07001622 // A request for HW A/V sync cannot fallback to a mixed output because time
1623 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001624 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001625 return AUDIO_IO_HANDLE_NONE;
1626 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001627 // A request for Tuner cannot fallback to a mixed output
1628 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1629 return AUDIO_IO_HANDLE_NONE;
1630 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001631
Eric Laurente552edb2014-03-10 17:42:56 -07001632 // ignoring channel mask due to downmix capability in mixer
1633
1634 // open a non direct output
1635
1636 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001637 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001638 // get which output is suitable for the specified stream. The actual
1639 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001640 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001641 if (prefMixerConfigInfo != nullptr) {
1642 for (audio_io_handle_t outputHandle : outputs) {
1643 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1644 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1645 output = outputHandle;
1646 break;
1647 }
1648 }
1649 if (output == AUDIO_IO_HANDLE_NONE) {
1650 // No output open with the preferred profile. Open a new one.
1651 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1652 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1653 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1654 config.format = prefMixerConfigInfo->getConfigBase().format;
1655 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1656 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1657 &config, prefMixerConfigInfo->getFlags());
1658 if (preferredOutput == nullptr) {
1659 ALOGE("%s failed to open output with preferred mixer config", __func__);
1660 } else {
1661 output = preferredOutput->mIoHandle;
1662 }
1663 }
1664 } else {
1665 // at this stage we should ignore the DIRECT flag as no direct output could be
1666 // found earlier
1667 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1668 output = selectOutput(
1669 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1670 }
Eric Laurente552edb2014-03-10 17:42:56 -07001671 }
François Gaffie11d30102018-11-02 16:09:09 +01001672 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001673 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001674 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001675
Eric Laurente552edb2014-03-10 17:42:56 -07001676 return output;
1677}
1678
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001679sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001680 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1681 mAvailableInputDevices);
1682 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1683}
1684
1685DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1686 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1687 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001688}
1689
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001690const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001691 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001692 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1693 if (msdModule != 0) {
1694 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1695 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1696 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1697 const struct audio_port_config *source = &patch->mPatch.sources[j];
1698 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1699 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001700 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001701 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001702 }
1703 }
1704 }
1705 return msdPatches;
1706}
1707
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001708bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1709 ssize_t index = mAudioPatches.indexOfKey(handle);
1710 if (index < 0) {
1711 return false;
1712 }
1713 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1714 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1715 if (msdModule == nullptr) {
1716 return false;
1717 }
1718 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1719 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1720 return true;
1721 }
1722 index = getMsdOutputPatches().indexOfKey(handle);
1723 if (index < 0) {
1724 return false;
1725 }
1726 return true;
1727}
1728
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001729status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1730 const InputProfileCollection &inputProfiles,
1731 const OutputProfileCollection &outputProfiles,
1732 const sp<DeviceDescriptor> &sourceDevice,
1733 const sp<DeviceDescriptor> &sinkDevice,
1734 AudioProfileVector& sourceProfiles,
1735 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001736 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001737 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001738 return NO_INIT;
1739 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001740 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001741 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001742 return NO_INIT;
1743 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001744 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001745 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1746 inProfile->supportsDevice(sourceDevice)) {
1747 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001748 }
1749 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001750 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001751 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001752 outProfile->supportsDevice(sinkDevice)) {
1753 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001754 }
1755 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001756 return NO_ERROR;
1757}
1758
1759status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1760 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1761 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1762{
Dean Wheatley16809da2022-12-09 14:55:46 +11001763 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1764 static const std::vector<audio_format_t> formatsOrder = {{
1765 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001766 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1767 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001768 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1769 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1770 // preferred).
1771 std::vector<audio_channel_mask_t> masks = {{
1772 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1773 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1774 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1775 // insert index masks (higher counts most preferred) as preferred over position masks
1776 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1777 masks.insert(
1778 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1779 }
1780 return masks;
1781 }();
1782
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001783 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001784 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1785 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001786 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001787 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1788 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001789 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001790 }
1791 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1792 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1793 sinkConfig->format = bestSinkConfig.format;
1794 // For encoded streams force direct flag to prevent downstream mixing.
1795 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1796 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001797 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1798 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001799 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001800 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1801 // raw and IEC61937 framed streams.
1802 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1803 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1804 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001805 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1806 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001807 sourceConfig->channel_mask =
1808 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1809 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1810 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001811 sourceConfig->format = bestSinkConfig.format;
1812 // Copy input stream directly without any processing (e.g. resampling).
1813 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1814 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1815 if (hwAvSync) {
1816 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1817 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1818 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1819 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1820 }
1821 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1822 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1823 sinkConfig->config_mask |= config_mask;
1824 sourceConfig->config_mask |= config_mask;
1825 return NO_ERROR;
1826}
1827
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001828PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1829 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001830{
1831 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001832 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1833 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1834 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1835 if (deviceModule == nullptr) {
1836 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1837 return patchBuilder;
1838 }
1839 const InputProfileCollection inputProfiles = msdIsSource ?
1840 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1841 const OutputProfileCollection outputProfiles = msdIsSource ?
1842 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1843
1844 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1845 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1846 device : getMsdAudioOutDevices().itemAt(0);
1847 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1848
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001849 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1850 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001851 AudioProfileVector sourceProfiles;
1852 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001853 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1854 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001855 for (auto hwAvSync : { true, false }) {
1856 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1857 sourceProfiles, sinkProfiles) != NO_ERROR) {
1858 continue;
1859 }
1860 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1861 &sinkConfig) == NO_ERROR) {
1862 // Found a matching config. Re-create PatchBuilder with this config.
1863 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1864 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001865 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001866 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001867 " supporting PCM format conversion.", __func__);
1868 return patchBuilder;
1869}
1870
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001871status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001872 DeviceVector devices;
1873 if (outputDevices != nullptr && outputDevices->size() > 0) {
1874 devices.add(*outputDevices);
1875 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001876 // Use media strategy for unspecified output device. This should only
1877 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1878 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001879 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001880 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001881 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001882 }
Michael Chan6fb34492020-12-08 15:44:49 +11001883 std::vector<PatchBuilder> patchesToCreate;
1884 for (auto i = 0u; i < devices.size(); ++i) {
1885 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001886 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001887 }
1888 // Retain only the MSD patches associated with outputDevices request.
1889 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001890 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001891 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1892 auto retainedPatch = false;
1893 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1894 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1895 patchesToRemove.removeItemsAt(i);
1896 retainedPatch = true;
1897 break;
1898 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001899 }
Michael Chan6fb34492020-12-08 15:44:49 +11001900 if (retainedPatch) {
1901 it = patchesToCreate.erase(it);
1902 continue;
1903 }
1904 ++it;
1905 }
1906 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1907 return NO_ERROR;
1908 }
1909 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1910 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001911 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001912 }
Michael Chan6fb34492020-12-08 15:44:49 +11001913 status_t status = NO_ERROR;
1914 for (const auto &p : patchesToCreate) {
1915 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1916 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1917 char message[256];
1918 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1919 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1920 currStatus == NO_ERROR ? "Success" : "Error",
1921 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1922 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1923 if (currStatus == NO_ERROR) {
1924 ALOGD("%s", message);
1925 } else {
1926 ALOGE("%s", message);
1927 if (status == NO_ERROR) {
1928 status = currStatus;
1929 }
1930 }
1931 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001932 return status;
1933}
1934
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001935void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1936 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001937 for (size_t i = 0; i < msdPatches.size(); i++) {
1938 const auto& patch = msdPatches[i];
1939 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1940 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1941 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1942 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1943 releaseAudioPatch(patch->getHandle(), mUidCached);
1944 break;
1945 }
1946 }
1947 }
1948}
1949
Dorin Drimus94d94412022-02-02 09:05:02 +01001950bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001951 DeviceVector devicesToCheck =
1952 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001953 AudioPatchCollection msdPatches = getMsdOutputPatches();
1954 for (size_t i = 0; i < msdPatches.size(); i++) {
1955 const auto& patch = msdPatches[i];
1956 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1957 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1958 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1959 const auto& foundDevice = devicesToCheck.getDevice(
1960 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1961 if (foundDevice != nullptr) {
1962 devicesToCheck.remove(foundDevice);
1963 if (devicesToCheck.isEmpty()) {
1964 return true;
1965 }
1966 }
1967 }
1968 }
1969 }
1970 return false;
1971}
1972
Eric Laurente0720872014-03-11 09:30:41 -07001973audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001974 audio_output_flags_t flags,
1975 audio_format_t format,
1976 audio_channel_mask_t channelMask,
1977 uint32_t samplingRate,
1978 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001979{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001980 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1981 "%s called with format %#x", __func__, format);
1982
jiabinebb6af42020-06-09 17:31:17 -07001983 // Return the output that haptic-generating attached to when 1) session id is specified,
1984 // 2) haptic-generating effect exists for given session id and 3) the output that
1985 // haptic-generating effect attached to is in given outputs.
1986 if (sessionId != AUDIO_SESSION_NONE) {
1987 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1988 sessionId, FX_IID_HAPTICGENERATOR);
1989 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1990 return hapticGeneratingOutput;
1991 }
1992 }
1993
Eric Laurent16c66dd2019-05-01 17:54:10 -07001994 // Flags disqualifying an output: the match must happen before calling selectOutput()
1995 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1996 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1997
1998 // Flags expressing a functional request: must be honored in priority over
1999 // other criteria
2000 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2001 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002002 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2003 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002004 // Flags expressing a performance request: have lower priority than serving
2005 // requested sampling rate or channel mask
2006 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2007 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2008 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2009
2010 const audio_output_flags_t functionalFlags =
2011 (audio_output_flags_t)(flags & kFunctionalFlags);
2012 const audio_output_flags_t performanceFlags =
2013 (audio_output_flags_t)(flags & kPerformanceFlags);
2014
2015 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2016
Eric Laurente552edb2014-03-10 17:42:56 -07002017 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002018 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002019 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002020 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002021 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002022 // with tiebreak preferring the minimum number of extra functional flags
2023 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002024 // 3: the output supporting the exact channel mask
2025 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002026 // 5: the output with the highest sampling rate if the requested sample rate is
2027 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002028 // 6: the output with the highest number of requested performance flags
2029 // 7: the output with the bit depth the closest to the requested one
2030 // 8: the primary output
2031 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002032
Eric Laurent16c66dd2019-05-01 17:54:10 -07002033 // matching criteria values in priority order for best matching output so far
2034 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002035
Eric Laurent16c66dd2019-05-01 17:54:10 -07002036 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2037 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2038 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002039
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002040 for (audio_io_handle_t output : outputs) {
2041 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002042 // matching criteria values in priority order for current output
2043 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002044
Eric Laurent16c66dd2019-05-01 17:54:10 -07002045 if (outputDesc->isDuplicated()) {
2046 continue;
2047 }
2048 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2049 continue;
2050 }
Eric Laurent8838a382014-09-08 16:44:28 -07002051
Eric Laurent16c66dd2019-05-01 17:54:10 -07002052 // If haptic channel is specified, use the haptic output if present.
2053 // When using haptic output, same audio format and sample rate are required.
2054 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002055 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002056 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2057 continue;
2058 }
2059 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002060 && format == outputDesc->getFormat()
2061 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002062 currentMatchCriteria[0] = outputHapticChannelCount;
2063 }
2064
2065 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002066 const int matchingFunctionalFlags =
2067 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2068 const int totalFunctionalFlags =
2069 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2070 // Prefer matching functional flags, but subtract unnecessary functional flags.
2071 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002072
2073 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002074 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2075 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002076 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2077 channelCount <= outputChannelCount) {
2078 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002079 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2080 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002081 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002082 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002083 currentMatchCriteria[3] = outputChannelCount;
2084 }
2085
2086 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002087 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002088 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002089 }
2090
2091 // performance flags match
2092 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2093
2094 // format match
2095 if (format != AUDIO_FORMAT_INVALID) {
2096 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002097 PolicyAudioPort::kFormatDistanceMax -
2098 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002099 }
2100
2101 // primary output match
2102 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2103
2104 // compare match criteria by priority then value
2105 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2106 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2107 bestMatchCriteria = currentMatchCriteria;
2108 bestOutput = output;
2109
2110 std::stringstream result;
2111 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2112 std::ostream_iterator<int>(result, " "));
2113 ALOGV("%s new bestOutput %d criteria %s",
2114 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002115 }
2116 }
2117
Eric Laurent16c66dd2019-05-01 17:54:10 -07002118 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002119}
2120
Eric Laurent8fc147b2018-07-22 19:13:55 -07002121status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002122{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002123 ALOGV("%s portId %d", __FUNCTION__, portId);
2124
2125 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2126 if (outputDesc == 0) {
2127 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002128 return BAD_VALUE;
2129 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002130 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002131
Eric Laurent8fc147b2018-07-22 19:13:55 -07002132 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002133 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002134
Eric Laurent733ce942017-12-07 12:18:25 -08002135 status_t status = outputDesc->start();
2136 if (status != NO_ERROR) {
2137 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002138 }
2139
Eric Laurent97ac8712018-07-27 18:59:02 -07002140 uint32_t delayMs;
2141 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002142
2143 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002144 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002145 if (status == DEAD_OBJECT) {
2146 sp<SwAudioOutputDescriptor> desc =
2147 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2148 if (desc == nullptr) {
2149 // This is not common, it may indicate something wrong with the HAL.
2150 ALOGE("%s unable to open output with default config", __func__);
2151 return status;
2152 }
2153 desc->mUsePreferredMixerAttributes = true;
2154 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002155 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002156 }
jiabina84c3d32022-12-02 18:59:55 +00002157
2158 // If the client is the first one active on preferred mixer parameters, reopen the output
2159 // if the current mixer parameters doesn't match the preferred one.
2160 if (outputDesc->devices().size() == 1) {
2161 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2162 outputDesc->devices()[0]->getId(), client->strategy());
2163 if (info != nullptr && info->getUid() == client->uid()) {
2164 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2165 info->getConfigBase(), info->getFlags())) {
2166 stopSource(outputDesc, client);
2167 outputDesc->stop();
2168 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2169 config.channel_mask = info->getConfigBase().channel_mask;
2170 config.sample_rate = info->getConfigBase().sample_rate;
2171 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002172 sp<SwAudioOutputDescriptor> desc =
2173 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2174 if (desc == nullptr) {
2175 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002176 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002177 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002178 // Intentionally return error to let the client side resending request for
2179 // creating and starting.
2180 return DEAD_OBJECT;
2181 }
2182 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002183 if (info->getActiveClientCount() == 1 &&
2184 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2185 // If it is first bit-perfect client, reroute all clients that will be routed to
2186 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2187 PortHandleVector clientsToInvalidate;
2188 for (size_t i = 0; i < mOutputs.size(); i++) {
2189 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002190 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002191 continue;
2192 }
2193 for (const auto& c : mOutputs[i]->getClientIterable()) {
2194 clientsToInvalidate.push_back(c->portId());
2195 }
2196 }
2197 if (!clientsToInvalidate.empty()) {
2198 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2199 __func__);
2200 mpClientInterface->invalidateTracks(clientsToInvalidate);
2201 }
2202 }
jiabina84c3d32022-12-02 18:59:55 +00002203 }
2204 }
2205
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002206 if (client->hasPreferredDevice()) {
2207 // playback activity with preferred device impacts routing occurred, inform upper layers
2208 mpClientInterface->onRoutingUpdated();
2209 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002210 if (delayMs != 0) {
2211 usleep(delayMs * 1000);
2212 }
2213
2214 return status;
2215}
2216
Eric Laurent96d1dda2022-03-14 17:14:19 +01002217bool AudioPolicyManager::isLeUnicastActive() const {
2218 if (isInCall()) {
2219 return true;
2220 }
2221 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2222}
2223
2224bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2225 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2226 return false;
2227 }
2228 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2229 ALOGV("%s active %d", __func__, active);
2230 return active;
2231}
2232
Eric Laurent97ac8712018-07-27 18:59:02 -07002233status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2234 const sp<TrackClientDescriptor>& client,
2235 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002236{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002237 // cannot start playback of STREAM_TTS if any other output is being used
2238 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002239
2240 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002241 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002242 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002243 auto clientStrategy = client->strategy();
2244 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002245 if (stream == AUDIO_STREAM_TTS) {
2246 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002247 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002248 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002249 return INVALID_OPERATION;
2250 } else {
2251 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2252 }
2253 } else {
2254 // some playback other than beacon starts
2255 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2256 }
2257
Eric Laurent77305a62016-07-25 16:39:22 -07002258 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002259 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002260 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002261
François Gaffie11d30102018-11-02 16:09:09 +01002262 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002263 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002264 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002265 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002266 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002267 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002268 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002269 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002270 } else {
2271 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002272 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002273 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2274 AUDIO_FORMAT_DEFAULT);
2275 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2276 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002277 }
2278
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002279 // requiresMuteCheck is false when we can bypass mute strategy.
2280 // It covers a common case when there is no materially active audio
2281 // and muting would result in unnecessary delay and dropped audio.
2282 const uint32_t outputLatencyMs = outputDesc->latency();
2283 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002284 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002285
Eric Laurente552edb2014-03-10 17:42:56 -07002286 // increment usage count for this stream on the requested output:
2287 // NOTE that the usage count is the same for duplicated output and hardware output which is
2288 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002289 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002290
2291 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002292 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002293 // Preferred device may be exclusive, use only if no other active clients on this output
2294 devices = DeviceVector(
2295 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2296 } else {
2297 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2298 }
François Gaffie11d30102018-11-02 16:09:09 +01002299 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002300 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002301 }
2302 }
Eric Laurente552edb2014-03-10 17:42:56 -07002303
François Gaffiec005e562018-11-06 15:04:49 +01002304 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002305 selectOutputForMusicEffects();
2306 }
2307
François Gaffie1c878552018-11-22 16:53:21 +01002308 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002309 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002310 if (devices.isEmpty()) {
2311 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002312 }
François Gaffiec005e562018-11-06 15:04:49 +01002313 bool shouldWait =
2314 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2315 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2316 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002317 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002318 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002319 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002320 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002321 // An output has a shared device if
2322 // - managed by the same hw module
2323 // - supports the currently selected device
2324 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002325 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002326
Eric Laurent77305a62016-07-25 16:39:22 -07002327 // force a device change if any other output is:
2328 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002329 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002330 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002331 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002332 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002333 // change the device currently selected by the other output.
2334 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002335 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002336 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002337 force = true;
2338 }
2339 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002340 // a notification so that audio focus effect can propagate, or that a mute/unmute
2341 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002342 const uint32_t latencyMs = desc->latency();
2343 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2344
2345 if (shouldWait && isActive && (waitMs < latencyMs)) {
2346 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002347 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002348
2349 // Require mute check if another output is on a shared device
2350 // and currently active to have proper drain and avoid pops.
2351 // Note restoring AudioTracks onto this output needs to invoke
2352 // a volume ramp if there is no mute.
2353 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002354 }
2355 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002356
jiabin3ff8d7d2022-12-13 06:27:44 +00002357 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2358 // If the output is open with preferred mixer attributes, but the routed device is
2359 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2360 // changed.
2361 return DEAD_OBJECT;
2362 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002363 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302364 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2365 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002366
Eric Laurente552edb2014-03-10 17:42:56 -07002367 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002368 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002369 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002370 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002371 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002372 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002373 outputDesc->useHwGain() /*force*/)) {
2374 // request AudioService to reinitialize the volume curves asynchronously
2375 ALOGE("checkAndSetVolume failed, requesting volume range init");
2376 mpClientInterface->onVolumeRangeInitRequest();
2377 };
Eric Laurente552edb2014-03-10 17:42:56 -07002378
2379 // update the outputs if starting an output with a stream that can affect notification
2380 // routing
2381 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002382
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002383 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002384 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002385 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002386 }
Eric Laurentdc462862016-07-19 12:29:53 -07002387
2388 if (waitMs > muteWaitMs) {
2389 *delayMs = waitMs - muteWaitMs;
2390 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002391
2392 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2393 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2394 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2395 // change occurs after the MixerThread starts and causes a stream volume
2396 // glitch.
2397 //
2398 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002399 }
Eric Laurentdc462862016-07-19 12:29:53 -07002400
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002401 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002402 mEngine->getForceUse(
2403 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002404 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002405 }
2406
Eric Laurent97ac8712018-07-27 18:59:02 -07002407 // Automatically enable the remote submix input when output is started on a re routing mix
2408 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002409 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2410 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002411 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2412 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2413 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002414 "remote-submix",
2415 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002416 }
2417
Eric Laurent96d1dda2022-03-14 17:14:19 +01002418 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2419
Eric Laurente552edb2014-03-10 17:42:56 -07002420 return NO_ERROR;
2421}
2422
Eric Laurent96d1dda2022-03-14 17:14:19 +01002423void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2424 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2425 bool isUnicastActive = isLeUnicastActive();
2426
2427 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002428 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002429 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2430 for (size_t i = 0; i < mOutputs.size(); i++) {
2431 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2432 if (desc != ignoredOutput && desc->isActive()
2433 && ((isUnicastActive &&
2434 !desc->devices().
2435 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2436 || (wasUnicastActive &&
2437 !desc->devices().getDevicesFromTypes(
2438 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2439 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2440 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002441 if (desc->mUsePreferredMixerAttributes && force) {
2442 // If the device is using preferred mixer attributes, the output need to reopen
2443 // with default configuration when the new selected devices are different from
2444 // current routing devices.
2445 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2446 continue;
2447 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302448 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002449 // re-apply device specific volume if not done by setOutputDevice()
2450 if (!force) {
2451 applyStreamVolumes(desc, newDevices.types(), delayMs);
2452 }
2453 }
2454 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002455 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002456 }
2457}
2458
Eric Laurent8fc147b2018-07-22 19:13:55 -07002459status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002460{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002461 ALOGV("%s portId %d", __FUNCTION__, portId);
2462
2463 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2464 if (outputDesc == 0) {
2465 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002466 return BAD_VALUE;
2467 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002468 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002469
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002470 if (client->hasPreferredDevice(true)) {
2471 // playback activity with preferred device impacts routing occurred, inform upper layers
2472 mpClientInterface->onRoutingUpdated();
2473 }
2474
Eric Laurent97ac8712018-07-27 18:59:02 -07002475 ALOGV("stopOutput() output %d, stream %d, session %d",
2476 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002477
Eric Laurent97ac8712018-07-27 18:59:02 -07002478 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002479
Eric Laurent733ce942017-12-07 12:18:25 -08002480 if (status == NO_ERROR ) {
2481 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002482 } else {
2483 return status;
2484 }
2485
2486 if (outputDesc->devices().size() == 1) {
2487 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2488 outputDesc->devices()[0]->getId(), client->strategy());
2489 if (info != nullptr && info->getUid() == client->uid()) {
2490 info->decreaseActiveClient();
2491 if (info->getActiveClientCount() == 0) {
2492 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2493 }
2494 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002495 }
2496 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002497}
2498
Eric Laurent97ac8712018-07-27 18:59:02 -07002499status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2500 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002501{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002502 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002503 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002504 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002505 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002506
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002507 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2508
François Gaffie1c878552018-11-22 16:53:21 +01002509 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2510 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002511 // Automatically disable the remote submix input when output is stopped on a
2512 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002513 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002514 if (isSingleDeviceType(
2515 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002516 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002517 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002518 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2519 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002520 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002521 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002522 }
2523 }
2524 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002525 if (client->hasPreferredDevice(true) &&
2526 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002527 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002528 forceDeviceUpdate = true;
2529 }
2530
Eric Laurente552edb2014-03-10 17:42:56 -07002531 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002532 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002533
Eric Laurente552edb2014-03-10 17:42:56 -07002534 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002535 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002536 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002537 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002538
2539 // If the routing does not change, if an output is routed on a device using HwGain
2540 // (aka setAudioPortConfig) and there are still active clients following different
2541 // volume group(s), force reapply volume
2542 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2543 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2544
Eric Laurente552edb2014-03-10 17:42:56 -07002545 // delay the device switch by twice the latency because stopOutput() is executed when
2546 // the track stop() command is received and at that time the audio track buffer can
2547 // still contain data that needs to be drained. The latency only covers the audio HAL
2548 // and kernel buffers. Also the latency does not always include additional delay in the
2549 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302550 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002551 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002552
2553 // force restoring the device selection on other active outputs if it differs from the
2554 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002555 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002556 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002557 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002558 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002559 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002560 desc->isActive() &&
2561 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002562 (newDevices != desc->devices())) {
2563 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2564 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002565
jiabin3ff8d7d2022-12-13 06:27:44 +00002566 if (desc->mUsePreferredMixerAttributes && force) {
2567 // If the device is using preferred mixer attributes, the output need to
2568 // reopen with default configuration when the new selected devices are
2569 // different from current routing devices.
2570 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2571 continue;
2572 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302573 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002574
Eric Laurent57de36c2016-09-28 16:59:11 -07002575 // re-apply device specific volume if not done by setOutputDevice()
2576 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002577 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002578 }
Eric Laurente552edb2014-03-10 17:42:56 -07002579 }
2580 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002581 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002582 // update the outputs if stopping one with a stream that can affect notification routing
2583 handleNotificationRoutingForStream(stream);
2584 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002585
2586 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2587 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002588 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002589 }
2590
François Gaffiec005e562018-11-06 15:04:49 +01002591 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002592 selectOutputForMusicEffects();
2593 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002594
2595 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2596
Eric Laurente552edb2014-03-10 17:42:56 -07002597 return NO_ERROR;
2598 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002599 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002600 return INVALID_OPERATION;
2601 }
2602}
2603
jiabinbce0c1d2020-10-05 11:20:18 -07002604bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002605{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002606 ALOGV("%s portId %d", __FUNCTION__, portId);
2607
2608 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2609 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002610 // If an output descriptor is closed due to a device routing change,
2611 // then there are race conditions with releaseOutput from tracks
2612 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2613 // destroyed shortly thereafter.
2614 //
2615 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002616 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002617 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002618 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002619
2620 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002621
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302622 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2623 if (outputDesc->isClientActive(client)) {
2624 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2625 stopOutput(portId);
2626 }
2627
Eric Laurent8fc147b2018-07-22 19:13:55 -07002628 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2629 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002630 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002631 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002632 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002633 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002634 if (--outputDesc->mDirectOpenCount == 0) {
2635 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002636 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002637 }
2638 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302639
Andy Hung39efb7a2018-09-26 15:39:28 -07002640 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002641 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2642 // The output is pending reopened to query dynamic profiles and
2643 // there is no active clients
2644 closeOutput(outputDesc->mIoHandle);
2645 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2646 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2647 if (newOutputDesc == nullptr) {
2648 ALOGE("%s failed to open output", __func__);
2649 }
2650 return true;
2651 }
2652 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002653}
2654
Eric Laurentcaf7f482014-11-25 17:50:47 -08002655status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2656 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002657 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002658 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002659 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002660 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002661 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002662 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002663 input_type_t *inputType,
2664 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002665{
François Gaffiec005e562018-11-06 15:04:49 +01002666 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002667 "flags %#x attributes=%s requested device ID %d",
2668 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2669 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002670
Eric Laurentad2e7b92017-09-14 20:06:42 -07002671 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002672 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002673 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002674 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002675 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002676 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002677 sp<RecordClientDescriptor> clientDesc;
2678 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002679 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002680 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002681
2682 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2683 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2684 return INVALID_OPERATION;
2685 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002686
Francois Gaffie716e1432019-01-14 16:58:59 +01002687 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2688 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002689 }
2690
Paul McLean466dc8e2015-04-17 13:15:36 -06002691 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002692 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002693 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002694
Eric Laurentad2e7b92017-09-14 20:06:42 -07002695 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2696 // possible
2697 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2698 *input != AUDIO_IO_HANDLE_NONE) {
2699 ssize_t index = mInputs.indexOfKey(*input);
2700 if (index < 0) {
2701 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2702 status = BAD_VALUE;
2703 goto error;
2704 }
2705 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002706 RecordClientVector clients = inputDesc->getClientsForSession(session);
2707 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002708 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2709 status = BAD_VALUE;
2710 goto error;
2711 }
2712 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2713 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002714 // corresponds to a new client and is only permitted from the same UID.
2715 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002716 if (clients.size() > 1) {
2717 for (const auto& client : clients) {
2718 // The client map is ordered by key values (portId) and portIds are allocated
2719 // incrementaly. So the first client in this list is the one opened by audio flinger
2720 // when the mmap stream is created and should be ignored as it does not correspond
2721 // to an actual client
2722 if (client == *clients.cbegin()) {
2723 continue;
2724 }
2725 if (uid != client->uid() && !client->isSilenced()) {
2726 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2727 uid, client->portId(), client->uid());
2728 status = INVALID_OPERATION;
2729 goto error;
2730 }
Eric Laurent331679c2018-04-16 17:03:16 -07002731 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002732 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002733 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002734 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002735
Eric Laurentfecbceb2021-02-09 14:46:43 +01002736 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002737 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002738 }
2739
2740 *input = AUDIO_IO_HANDLE_NONE;
2741 *inputType = API_INPUT_INVALID;
2742
Francois Gaffie716e1432019-01-14 16:58:59 +01002743 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002744 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002745 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002746 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002747 ALOGW("%s could not find input mix for attr %s",
2748 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002749 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002750 }
jiabinc1de2df2019-05-07 14:26:40 -07002751 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2752 String8(attr->tags + strlen("addr=")),
2753 AUDIO_FORMAT_DEFAULT);
2754 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002755 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002756 __func__, attributes.source, attributes.tags);
2757 status = BAD_VALUE;
2758 goto error;
2759 }
2760
Kevin Rocard25f9b052019-02-27 15:08:54 -08002761 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2762 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2763 } else {
2764 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2765 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002766 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002767 if (explicitRoutingDevice != nullptr) {
2768 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002769 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002770 // Prevent from storing invalid requested device id in clients
2771 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002772 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002773 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2774 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002775 }
François Gaffie11d30102018-11-02 16:09:09 +01002776 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002777 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002778 status = BAD_VALUE;
2779 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002780 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002781 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2782 *inputType = API_INPUT_MIX_CAPTURE;
2783 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002784 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2785 // there is an external policy, but this input is attached to a mix of recorders,
2786 // meaning it receives audio injected into the framework, so the recorder doesn't
2787 // know about it and is therefore considered "legacy"
2788 *inputType = API_INPUT_LEGACY;
2789 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002790 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002791 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002792 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002793 } else {
2794 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002795 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002796
Eric Laurent599c7582015-12-07 18:05:55 -08002797 }
2798
François Gaffiec005e562018-11-06 15:04:49 +01002799 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002800 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002801 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002802 AudioProfileVector profiles;
2803 status_t ret = getProfilesForDevices(
2804 DeviceVector(device), profiles, flags, true /*isInput*/);
2805 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002806 const auto channels = profiles[0]->getChannels();
2807 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2808 config->channel_mask = *channels.begin();
2809 }
2810 const auto sampleRates = profiles[0]->getSampleRates();
2811 if (!sampleRates.empty() &&
2812 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2813 config->sample_rate = *sampleRates.begin();
2814 }
jiabinf1c73972022-04-14 16:28:52 -07002815 config->format = profiles[0]->getFormat();
2816 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002817 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002818 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002819
Eric Laurent8f42ea12018-08-08 09:08:25 -07002820exit:
2821
François Gaffiec005e562018-11-06 15:04:49 +01002822 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2823 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002824
Francois Gaffie716e1432019-01-14 16:58:59 +01002825 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002826 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002827 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002828
Mikhail Naganov2996f672019-04-18 12:29:59 -07002829 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002830 requestedDeviceId, attributes.source, flags,
2831 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002832 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002833 // Move (if found) effect for the client session to its input
2834 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002835 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002836
2837 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2838 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002839
Eric Laurent599c7582015-12-07 18:05:55 -08002840 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002841
2842error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002843 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002844}
2845
2846
François Gaffie11d30102018-11-02 16:09:09 +01002847audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002848 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002849 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002850 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002851 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002852 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002853{
2854 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002855 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002856 bool isSoundTrigger = false;
2857
François Gaffiec005e562018-11-06 15:04:49 +01002858 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002859 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2860 if (index >= 0) {
2861 input = mSoundTriggerSessions.valueFor(session);
2862 isSoundTrigger = true;
2863 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2864 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2865 } else {
2866 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002867 }
François Gaffiec005e562018-11-06 15:04:49 +01002868 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002869 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002870 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002871 }
2872
Carter Hsua3abb402021-10-26 11:11:20 +08002873 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2874 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2875 }
2876
Eric Laurentfe231122017-11-17 17:48:06 -08002877 // sampling rate and flags may be updated by getInputProfile
2878 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2879 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002880 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002881 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002882 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002883 // find a compatible input profile (not necessarily identical in parameters)
2884 sp<IOProfile> profile = getInputProfile(
2885 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2886 if (profile == nullptr) {
2887 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002888 }
jiabin2fd710d2022-05-02 23:20:22 +00002889
Glenn Kasten05ddca52016-02-11 08:17:12 -08002890 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002891 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002892 if (samplingRate == 0) {
2893 samplingRate = profileSamplingRate;
2894 }
Eric Laurente552edb2014-03-10 17:42:56 -07002895
Eric Laurent322b4d22015-04-03 15:57:54 -07002896 if (profile->getModuleHandle() == 0) {
2897 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002898 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002899 }
2900
Eric Laurentec376dc2021-04-08 20:41:22 +02002901 // Reuse an already opened input if a client with the same session ID already exists
2902 // on that input
2903 for (size_t i = 0; i < mInputs.size(); i++) {
2904 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2905 if (desc->mProfile != profile) {
2906 continue;
2907 }
2908 RecordClientVector clients = desc->clientsList();
2909 for (const auto &client : clients) {
2910 if (session == client->session()) {
2911 return desc->mIoHandle;
2912 }
2913 }
2914 }
2915
Eric Laurent3974e3b2017-12-07 17:58:43 -08002916 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002917 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002918 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002919 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002920 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002921 continue;
2922 }
2923 // if sound trigger, reuse input if used by other sound trigger on same session
2924 // else
2925 // reuse input if active client app is not in IDLE state
2926 //
2927 RecordClientVector clients = desc->clientsList();
2928 bool doClose = false;
2929 for (const auto& client : clients) {
2930 if (isSoundTrigger != client->isSoundTrigger()) {
2931 continue;
2932 }
2933 if (client->isSoundTrigger()) {
2934 if (session == client->session()) {
2935 return desc->mIoHandle;
2936 }
2937 continue;
2938 }
2939 if (client->active() && client->appState() != APP_STATE_IDLE) {
2940 return desc->mIoHandle;
2941 }
2942 doClose = true;
2943 }
2944 if (doClose) {
2945 closeInput(desc->mIoHandle);
2946 } else {
2947 i++;
2948 }
2949 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002950 }
2951
Eric Laurentfe231122017-11-17 17:48:06 -08002952 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002953
Eric Laurentfe231122017-11-17 17:48:06 -08002954 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2955 lConfig.sample_rate = profileSamplingRate;
2956 lConfig.channel_mask = profileChannelMask;
2957 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002958
François Gaffie11d30102018-11-02 16:09:09 +01002959 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002960
2961 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002962 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002963 (profileSamplingRate != lConfig.sample_rate) ||
2964 !audio_formats_match(profileFormat, lConfig.format) ||
2965 (profileChannelMask != lConfig.channel_mask)) {
2966 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002967 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002968 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002969 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002970 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002971 }
Eric Laurent599c7582015-12-07 18:05:55 -08002972 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002973 }
2974
Eric Laurentc722f302014-12-10 11:21:49 -08002975 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002976
Eric Laurent599c7582015-12-07 18:05:55 -08002977 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002978 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002979
Eric Laurent599c7582015-12-07 18:05:55 -08002980 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002981}
2982
Eric Laurent4eb58f12018-12-07 16:41:02 -08002983status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002984{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002985 ALOGV("%s portId %d", __FUNCTION__, portId);
2986
2987 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2988 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002989 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002990 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002991 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002992 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002993 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002994 if (client->active()) {
2995 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2996 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002997 }
2998
Eric Laurent8f42ea12018-08-08 09:08:25 -07002999 audio_session_t session = client->session();
3000
Eric Laurent4eb58f12018-12-07 16:41:02 -08003001 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003002
Eric Laurent4eb58f12018-12-07 16:41:02 -08003003 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003004
Eric Laurent4eb58f12018-12-07 16:41:02 -08003005 status_t status = inputDesc->start();
3006 if (status != NO_ERROR) {
3007 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003008 }
Eric Laurente552edb2014-03-10 17:42:56 -07003009
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003010 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003011 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003012 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003013
Eric Laurent8f42ea12018-08-08 09:08:25 -07003014 // indicate active capture to sound trigger service if starting capture from a mic on
3015 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003016 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003017 if (device != nullptr) {
3018 status = setInputDevice(input, device, true /* force */);
3019 } else {
3020 ALOGW("%s no new input device can be found for descriptor %d",
3021 __FUNCTION__, inputDesc->getId());
3022 status = BAD_VALUE;
3023 }
Eric Laurente552edb2014-03-10 17:42:56 -07003024
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003025 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003026 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003027 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003028 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003029 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3030 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003031 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003032 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003033
François Gaffie11d30102018-11-02 16:09:09 +01003034 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3035 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003036 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003037 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003038 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003039
Eric Laurent8f42ea12018-08-08 09:08:25 -07003040 // automatically enable the remote submix output when input is started if not
3041 // used by a policy mix of type MIX_TYPE_RECORDERS
3042 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003043 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003044 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003045 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003046 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003047 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3048 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003049 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003050 if (address != "") {
3051 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3052 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003053 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003054 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003055 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003056 } else if (status != NO_ERROR) {
3057 // Restore client activity state.
3058 inputDesc->setClientActive(client, false);
3059 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003060 }
3061
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003062 ALOGV("%s input %d source = %d status = %d exit",
3063 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003064
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003065 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003066}
3067
Eric Laurent8fc147b2018-07-22 19:13:55 -07003068status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003069{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003070 ALOGV("%s portId %d", __FUNCTION__, portId);
3071
3072 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3073 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003074 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003075 return BAD_VALUE;
3076 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003077 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003078 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003079 if (!client->active()) {
3080 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003081 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003082 }
Carter Hsue6139d52021-07-08 10:30:20 +08003083 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003084 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003085
Eric Laurent8f42ea12018-08-08 09:08:25 -07003086 inputDesc->stop();
3087 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003088 auto current_source = inputDesc->source();
3089 setInputDevice(input, getNewInputDevice(inputDesc),
3090 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003091 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003092 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003093 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003094 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003095 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3096 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003097 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003098 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003099
3100 // automatically disable the remote submix output when input is stopped if not
3101 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003102 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003103 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003104 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003105 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003106 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3107 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003108 }
3109 if (address != "") {
3110 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3111 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003112 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003113 }
3114 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003115 resetInputDevice(input);
3116
3117 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3118 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003119 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3120 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003121 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003122 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003123 }
3124 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003125 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003126 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003127}
3128
Eric Laurent8fc147b2018-07-22 19:13:55 -07003129void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003130{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003131 ALOGV("%s portId %d", __FUNCTION__, portId);
3132
3133 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3134 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003135 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003136 return;
3137 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003138 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003139 audio_io_handle_t input = inputDesc->mIoHandle;
3140
Eric Laurent8f42ea12018-08-08 09:08:25 -07003141 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003142
Andy Hung39efb7a2018-09-26 15:39:28 -07003143 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003144 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003145 if (inputDesc->getClientCount() > 0) {
3146 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003147 return;
3148 }
3149
Eric Laurent05b90f82014-08-27 15:32:29 -07003150 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003151 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003152 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003153}
3154
Eric Laurent8f42ea12018-08-08 09:08:25 -07003155void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003156{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003157 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003158
3159 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003160 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003161 }
3162}
3163
Eric Laurent8f42ea12018-08-08 09:08:25 -07003164void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3165{
3166 stopInput(portId);
3167 releaseInput(portId);
3168}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003169
Eric Laurent0dd51852019-04-19 18:18:58 -07003170void AudioPolicyManager::checkCloseInputs() {
3171 // After connecting or disconnecting an input device, close input if:
3172 // - it has no client (was just opened to check profile) OR
3173 // - none of its supported devices are connected anymore OR
3174 // - one of its clients cannot be routed to one of its supported
3175 // devices anymore. Otherwise update device selection
3176 std::vector<audio_io_handle_t> inputsToClose;
3177 for (size_t i = 0; i < mInputs.size(); i++) {
3178 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3179 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003180 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003181 inputsToClose.push_back(mInputs.keyAt(i));
3182 } else {
3183 bool close = false;
3184 for (const auto& client : input->clientsList()) {
3185 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003186 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3187 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003188 if (!input->supportedDevices().contains(device)) {
3189 close = true;
3190 break;
3191 }
3192 }
3193 if (close) {
3194 inputsToClose.push_back(mInputs.keyAt(i));
3195 } else {
3196 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3197 }
3198 }
3199 }
3200
3201 for (const audio_io_handle_t handle : inputsToClose) {
3202 ALOGV("%s closing input %d", __func__, handle);
3203 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003204 }
Eric Laurentd4692962014-05-05 18:13:44 -07003205}
3206
François Gaffie251c7f02018-11-07 10:41:08 +01003207void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003208{
3209 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003210 if (indexMin < 0 || indexMax < 0) {
3211 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3212 return;
3213 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003214 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003215
3216 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003217 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3218 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003219 continue;
3220 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003221 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003222 }
Eric Laurente552edb2014-03-10 17:42:56 -07003223}
3224
Eric Laurente0720872014-03-11 09:30:41 -07003225status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003226 int index,
3227 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003228{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003229 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003230 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3231 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3232 return NO_ERROR;
3233 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003234 ALOGV("%s: stream %s attributes=%s", __func__,
3235 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003236 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003237}
3238
Eric Laurente0720872014-03-11 09:30:41 -07003239status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003240 int *index,
3241 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003242{
François Gaffiec005e562018-11-06 15:04:49 +01003243 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3244 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003245 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003246 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003247 deviceTypes = mEngine->getOutputDevicesForStream(
3248 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003249 }
jiabin9a3361e2019-10-01 09:38:30 -07003250 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003251}
3252
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003253status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003254 int index,
3255 audio_devices_t device)
3256{
3257 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003258 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3259 if (group == VOLUME_GROUP_NONE) {
3260 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003261 return BAD_VALUE;
3262 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003263 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003264 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003265 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003266 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003267 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3268 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3269 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3270 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003271 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3272
3273 status = setVolumeCurveIndex(index, device, curves);
3274 if (status != NO_ERROR) {
3275 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3276 return status;
3277 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003278
jiabin9a3361e2019-10-01 09:38:30 -07003279 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003280 auto curCurvAttrs = curves.getAttributes();
3281 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3282 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003283 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003284 } else if (!curves.getStreamTypes().empty()) {
3285 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003286 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003287 } else {
3288 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3289 return BAD_VALUE;
3290 }
jiabin9a3361e2019-10-01 09:38:30 -07003291 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3292 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003293
François Gaffiecfe17322018-11-07 13:41:29 +01003294 // update volume on all outputs and streams matching the following:
3295 // - The requested stream (or a stream matching for volume control) is active on the output
3296 // - The device (or devices) selected by the engine for this stream includes
3297 // the requested device
3298 // - For non default requested device, currently selected device on the output is either the
3299 // requested device or one of the devices selected by the engine for this stream
3300 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3301 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003302 for (size_t i = 0; i < mOutputs.size(); i++) {
3303 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003304 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003305
jiabin9a3361e2019-10-01 09:38:30 -07003306 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3307 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003308 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003309
3310 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003311 continue;
3312 }
3313 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3314 curDevices.find(device) == curDevices.end()) {
3315 continue;
3316 }
3317 bool applyVolume = false;
3318 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3319 curSrcDevices.insert(device);
3320 applyVolume = (curSrcDevices.find(
3321 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3322 } else {
3323 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3324 }
3325 if (!applyVolume) {
3326 continue; // next output
3327 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003328 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3329 // If a higher priority strategy is active, and the output is routed to a device with a
3330 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003331 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003332 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003333 // If the volume source is active with higher priority source, ensure at least Sw Muted
3334 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003335 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3336 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3337 false /*preferredDevice*/);
3338 if (activeClients.empty()) {
3339 continue;
3340 }
3341 bool isPreempted = false;
3342 bool isHigherPriority = productStrategy < strategy;
3343 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003344 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003345 ALOGV("%s: Strategy=%d (\nrequester:\n"
3346 " group %d, volumeGroup=%d attributes=%s)\n"
3347 " higher priority source active:\n"
3348 " volumeGroup=%d attributes=%s) \n"
3349 " on output %zu, bailing out", __func__, productStrategy,
3350 group, group, toString(attributes).c_str(),
3351 client->volumeSource(), toString(client->attributes()).c_str(), i);
3352 applyVolume = false;
3353 isPreempted = true;
3354 break;
3355 }
3356 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003357 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003358 applyVolume = true;
3359 }
3360 }
3361 if (isPreempted || applyVolume) {
3362 break;
3363 }
3364 }
3365 if (!applyVolume) {
3366 continue; // next output
3367 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003368 }
François Gaffieed91f582020-01-31 10:35:37 +01003369 //FIXME: workaround for truncated touch sounds
3370 // delayed volume change for system stream to be removed when the problem is
3371 // handled by system UI
3372 status_t volStatus = checkAndSetVolume(
3373 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003374 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003375 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3376 if (volStatus != NO_ERROR) {
3377 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003378 }
3379 }
François Gaffiecfe17322018-11-07 13:41:29 +01003380 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3381 return status;
3382}
3383
François Gaffieaaac0fd2018-11-22 17:56:39 +01003384status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003385 audio_devices_t device,
3386 IVolumeCurves &volumeCurves)
3387{
3388 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3389 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003390 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3391 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003392 (index > volumeCurves.getVolumeIndexMax())) {
3393 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3394 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3395 return BAD_VALUE;
3396 }
3397 if (!audio_is_output_device(device)) {
3398 return BAD_VALUE;
3399 }
3400
3401 // Force max volume if stream cannot be muted
3402 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3403
François Gaffieaaac0fd2018-11-22 17:56:39 +01003404 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003405 volumeCurves.addCurrentVolumeIndex(device, index);
3406 return NO_ERROR;
3407}
3408
3409status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3410 int &index,
3411 audio_devices_t device)
3412{
3413 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3414 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003415 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003416 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003417 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003418 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003419 }
jiabin9a3361e2019-10-01 09:38:30 -07003420 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003421}
3422
3423status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3424 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003425 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003426{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003427 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003428 return BAD_VALUE;
3429 }
jiabin9a3361e2019-10-01 09:38:30 -07003430 index = curves.getVolumeIndex(deviceTypes);
3431 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003432 return NO_ERROR;
3433}
3434
3435status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3436 int &index)
3437{
3438 index = getVolumeCurves(attr).getVolumeIndexMin();
3439 return NO_ERROR;
3440}
3441
3442status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3443 int &index)
3444{
3445 index = getVolumeCurves(attr).getVolumeIndexMax();
3446 return NO_ERROR;
3447}
3448
Eric Laurent36829f92017-04-07 19:04:42 -07003449audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003450{
3451 // select one output among several suitable for global effects.
3452 // The priority is as follows:
3453 // 1: An offloaded output. If the effect ends up not being offloadable,
3454 // AudioFlinger will invalidate the track and the offloaded output
3455 // will be closed causing the effect to be moved to a PCM output.
3456 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003457 // 3: The primary output
3458 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003459
François Gaffiec005e562018-11-06 15:04:49 +01003460 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3461 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003462 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003463
Eric Laurent36829f92017-04-07 19:04:42 -07003464 if (outputs.size() == 0) {
3465 return AUDIO_IO_HANDLE_NONE;
3466 }
Eric Laurente552edb2014-03-10 17:42:56 -07003467
Eric Laurent36829f92017-04-07 19:04:42 -07003468 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3469 bool activeOnly = true;
3470
3471 while (output == AUDIO_IO_HANDLE_NONE) {
3472 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3473 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3474 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3475
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003476 for (audio_io_handle_t output : outputs) {
3477 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003478 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003479 continue;
3480 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003481 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3482 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003483 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003484 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003485 }
3486 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003487 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003488 }
3489 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003490 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003491 }
3492 }
3493 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3494 output = outputOffloaded;
3495 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3496 output = outputDeepBuffer;
3497 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3498 output = outputPrimary;
3499 } else {
3500 output = outputs[0];
3501 }
3502 activeOnly = false;
3503 }
3504
3505 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003506 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3507 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003508 mMusicEffectOutput = output;
3509 }
3510
3511 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003512 return output;
3513}
3514
Eric Laurent36829f92017-04-07 19:04:42 -07003515audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3516{
3517 return selectOutputForMusicEffects();
3518}
3519
Eric Laurente0720872014-03-11 09:30:41 -07003520status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003521 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003522 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003523 int session,
3524 int id)
3525{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003526 if (session != AUDIO_SESSION_DEVICE) {
3527 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003528 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003529 index = mInputs.indexOfKey(io);
3530 if (index < 0) {
3531 ALOGW("registerEffect() unknown io %d", io);
3532 return INVALID_OPERATION;
3533 }
Eric Laurente552edb2014-03-10 17:42:56 -07003534 }
3535 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003536 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3537 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3538 || strategy == PRODUCT_STRATEGY_NONE));
3539 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003540}
3541
Eric Laurentc241b0d2018-11-28 09:08:49 -08003542status_t AudioPolicyManager::unregisterEffect(int id)
3543{
3544 if (mEffects.getEffect(id) == nullptr) {
3545 return INVALID_OPERATION;
3546 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003547 if (mEffects.isEffectEnabled(id)) {
3548 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3549 setEffectEnabled(id, false);
3550 }
3551 return mEffects.unregisterEffect(id);
3552}
3553
3554status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3555{
3556 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3557 if (effect == nullptr) {
3558 return INVALID_OPERATION;
3559 }
3560
3561 status_t status = mEffects.setEffectEnabled(id, enabled);
3562 if (status == NO_ERROR) {
3563 mInputs.trackEffectEnabled(effect, enabled);
3564 }
3565 return status;
3566}
3567
Eric Laurent6c796322019-04-09 14:13:17 -07003568
3569status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3570{
3571 mEffects.moveEffects(ids, io);
3572 return NO_ERROR;
3573}
3574
Eric Laurentc75307b2015-03-17 15:29:32 -07003575bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3576{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003577 auto vs = toVolumeSource(stream, false);
3578 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003579}
3580
3581bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3582{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003583 auto vs = toVolumeSource(stream, false);
3584 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003585}
3586
Eric Laurente0720872014-03-11 09:30:41 -07003587bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003588{
3589 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003590 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003591 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003592 return true;
3593 }
3594 }
3595 return false;
3596}
3597
Eric Laurent275e8e92014-11-30 15:14:47 -08003598// Register a list of custom mixes with their attributes and format.
3599// When a mix is registered, corresponding input and output profiles are
3600// added to the remote submix hw module. The profile contains only the
3601// parameters (sampling rate, format...) specified by the mix.
3602// The corresponding input remote submix device is also connected.
3603//
3604// When a remote submix device is connected, the address is checked to select the
3605// appropriate profile and the corresponding input or output stream is opened.
3606//
3607// When capture starts, getInputForAttr() will:
3608// - 1 look for a mix matching the address passed in attribtutes tags if any
3609// - 2 if none found, getDeviceForInputSource() will:
3610// - 2.1 look for a mix matching the attributes source
3611// - 2.2 if none found, default to device selection by policy rules
3612// At this time, the corresponding output remote submix device is also connected
3613// and active playback use cases can be transferred to this mix if needed when reconnecting
3614// after AudioTracks are invalidated
3615//
3616// When playback starts, getOutputForAttr() will:
3617// - 1 look for a mix matching the address passed in attribtutes tags if any
3618// - 2 if none found, look for a mix matching the attributes usage
3619// - 3 if none found, default to device and output selection by policy rules.
3620
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003621status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003622{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003623 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3624 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003625 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003626 sp<HwModule> rSubmixModule;
3627 // examine each mix's route type
3628 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003629 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003630 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3631 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3632 ALOGE("Unsupported Policy Mix %zu of %zu: "
3633 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3634 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003635 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003636 break;
3637 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003638 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3639 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003640 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003641 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3642 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003643 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003644 rSubmixModule = mHwModules.getModuleFromName(
3645 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3646 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003647 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003648 i);
3649 res = INVALID_OPERATION;
3650 break;
3651 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003652 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003653
Eric Laurent97ac8712018-07-27 18:59:02 -07003654 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003655 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003656 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003657 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003658 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3659 } else {
3660 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3661 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003662 }
François Gaffie036e1e92015-03-19 10:16:24 +01003663
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003664 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003665 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003666 res = INVALID_OPERATION;
3667 break;
3668 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003669 audio_config_t outputConfig = mix.mFormat;
3670 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003671 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3672 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003673 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3674 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003675 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003676 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3677 audio_is_linear_pcm(outputConfig.format)
3678 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003679 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003680 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3681 audio_is_linear_pcm(inputConfig.format)
3682 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003683
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003684 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003685 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003686 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003687 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003688 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003689 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003690 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003691 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3692 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003693 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003694 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003695 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003696
3697 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3698 mix.mDeviceType, mix.mDeviceAddress,
3699 String8(), AUDIO_FORMAT_DEFAULT);
3700 if (device == nullptr) {
3701 res = INVALID_OPERATION;
3702 break;
3703 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003704
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003705 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003706 // First try to find an already opened output supporting the device
3707 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003708 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003709
Eric Laurentc529cf62020-04-17 18:19:10 -07003710 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003711 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003712 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003713 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003714 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003715 } else {
3716 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003717 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003718 }
3719 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003720 // If no output found, try to find a direct output profile supporting the device
3721 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3722 sp<HwModule> module = mHwModules[i];
3723 for (size_t j = 0;
3724 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3725 j++) {
3726 sp<IOProfile> profile = module->getOutputProfiles()[j];
3727 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3728 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3729 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003730 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003731 res = INVALID_OPERATION;
3732 } else {
3733 foundOutput = true;
3734 }
3735 }
3736 }
3737 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003738 if (res != NO_ERROR) {
3739 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003740 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003741 res = INVALID_OPERATION;
3742 break;
3743 } else if (!foundOutput) {
3744 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003745 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003746 res = INVALID_OPERATION;
3747 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003748 } else {
3749 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003750 }
Eric Laurentc722f302014-12-10 11:21:49 -08003751 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003752 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003753 if (res != NO_ERROR) {
3754 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003755 } else if (checkOutputs) {
3756 checkForDeviceAndOutputChanges();
3757 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003758 }
3759 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003760}
3761
3762status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3763{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003764 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003765 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003766 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003767 sp<HwModule> rSubmixModule;
3768 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003769 for (const auto& mix : mixes) {
3770 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003771
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003772 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003773 rSubmixModule = mHwModules.getModuleFromName(
3774 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3775 if (rSubmixModule == 0) {
3776 res = INVALID_OPERATION;
3777 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003778 }
3779 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003780
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003781 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003782
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003783 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003784 res = INVALID_OPERATION;
3785 continue;
3786 }
3787
Kevin Rocard04ed0462019-05-02 17:53:24 -07003788 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003789 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003790 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3791 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003792 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003793 AUDIO_FORMAT_DEFAULT);
3794 if (res != OK) {
3795 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003796 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003797 }
3798 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003799 }
jiabin5740f082019-08-19 15:08:30 -07003800 rSubmixModule->removeOutputProfile(address.c_str());
3801 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003802
Kevin Rocard153f92d2018-12-18 18:33:28 -08003803 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003804 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003805 res = INVALID_OPERATION;
3806 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003807 } else {
3808 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003809 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003810 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003811 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003812 if (res == NO_ERROR && checkOutputs) {
3813 checkForDeviceAndOutputChanges();
3814 updateCallAndOutputRouting();
3815 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003816 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003817}
3818
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003819status_t AudioPolicyManager::updatePolicyMix(
3820 const AudioMix& mix,
3821 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3822 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3823 if (res == NO_ERROR) {
3824 checkForDeviceAndOutputChanges();
3825 updateCallAndOutputRouting();
3826 }
3827 return res;
3828}
3829
Mikhail Naganov100f0122018-11-29 11:22:16 -08003830void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3831{
3832 size_t i = 0;
3833 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3834 for (const auto& fmt : mManualSurroundFormats) {
3835 if (i++ != 0) dst->append(", ");
3836 std::string sfmt;
3837 FormatConverter::toString(fmt, sfmt);
3838 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3839 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3840 }
3841}
3842
Eric Laurentc529cf62020-04-17 18:19:10 -07003843// Returns true if all devices types match the predicate and are supported by one HW module
3844bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003845 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003846 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003847 const char *context,
3848 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003849 for (size_t i = 0; i < devices.size(); i++) {
3850 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003851 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003852 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003853 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003854 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003855 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003856 return false;
3857 }
3858 }
3859 return true;
3860}
3861
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003862void AudioPolicyManager::changeOutputDevicesMuteState(
3863 const AudioDeviceTypeAddrVector& devices) {
3864 ALOGVV("%s() num devices %zu", __func__, devices.size());
3865
3866 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3867 getSoftwareOutputsForDevices(devices);
3868
3869 for (size_t i = 0; i < outputs.size(); i++) {
3870 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3871 DeviceVector prevDevices = outputDesc->devices();
3872 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3873 }
3874}
3875
3876std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3877 const AudioDeviceTypeAddrVector& devices) const
3878{
3879 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3880 DeviceVector deviceDescriptors;
3881 for (size_t j = 0; j < devices.size(); j++) {
3882 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3883 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3884 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3885 ALOGE("%s: device type %#x address %s not supported or not an output device",
3886 __func__, devices[j].mType, devices[j].getAddress());
3887 continue;
3888 }
3889 deviceDescriptors.add(desc);
3890 }
3891 for (size_t i = 0; i < mOutputs.size(); i++) {
3892 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3893 continue;
3894 }
3895 outputs.push_back(mOutputs.valueAt(i));
3896 }
3897 return outputs;
3898}
3899
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003900status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003901 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003902 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003903 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3904 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003905 }
3906 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003907 if (res != NO_ERROR) {
3908 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3909 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003910 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003911
3912 checkForDeviceAndOutputChanges();
3913 updateCallAndOutputRouting();
3914
3915 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003916}
3917
3918status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3919 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003920 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3921 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003922 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003923 __FUNCTION__, uid);
3924 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003925 }
3926
Eric Laurentc529cf62020-04-17 18:19:10 -07003927 checkForDeviceAndOutputChanges();
3928 updateCallAndOutputRouting();
3929
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003930 return res;
3931}
3932
Eric Laurent2517af32020-11-25 15:31:27 +01003933
jiabin0a488932020-08-07 17:32:40 -07003934status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3935 device_role_t role,
3936 const AudioDeviceTypeAddrVector &devices) {
3937 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3938 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003939
Eric Laurentc529cf62020-04-17 18:19:10 -07003940 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003941 return BAD_VALUE;
3942 }
jiabin0a488932020-08-07 17:32:40 -07003943 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003944 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003945 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3946 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003947 return status;
3948 }
3949
3950 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003951
3952 bool forceVolumeReeval = false;
3953 // FIXME: workaround for truncated touch sounds
3954 // to be removed when the problem is handled by system UI
3955 uint32_t delayMs = 0;
3956 if (strategy == mCommunnicationStrategy) {
3957 forceVolumeReeval = true;
3958 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3959 updateInputRouting();
3960 }
3961 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003962
3963 return NO_ERROR;
3964}
3965
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003966void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
3967 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003968{
3969 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003970 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003971 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003972 // Only apply special touch sound delay once
3973 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003974 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003975 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003976 for (size_t i = 0; i < mOutputs.size(); i++) {
3977 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3978 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003979 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3980 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003981 // As done in setDeviceConnectionState, we could also fix default device issue by
3982 // preventing the force re-routing in case of default dev that distinguishes on address.
3983 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003984 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003985 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3986 // If the device is using preferred mixer attributes, the output need to reopen
3987 // with default configuration when the new selected devices are different from
3988 // current routing devices.
3989 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3990 continue;
3991 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05303992
3993 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
3994 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003995 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003996 // Only apply special touch sound delay once
3997 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003998 }
3999 if (forceVolumeReeval && !newDevices.isEmpty()) {
4000 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4001 }
4002 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004003 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004004 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004005}
4006
Eric Laurent2517af32020-11-25 15:31:27 +01004007void AudioPolicyManager::updateInputRouting() {
4008 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304009 // Skip for hotword recording as the input device switch
4010 // is handled within sound trigger HAL
4011 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4012 continue;
4013 }
Eric Laurent2517af32020-11-25 15:31:27 +01004014 auto newDevice = getNewInputDevice(activeDesc);
4015 // Force new input selection if the new device can not be reached via current input
4016 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4017 setInputDevice(activeDesc->mIoHandle, newDevice);
4018 } else {
4019 closeInput(activeDesc->mIoHandle);
4020 }
4021 }
4022}
4023
Paul Wang5d7cdb52022-11-22 09:45:06 +00004024status_t
4025AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4026 device_role_t role,
4027 const AudioDeviceTypeAddrVector &devices) {
4028 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4029 dumpAudioDeviceTypeAddrVector(devices).c_str());
4030
Eric Laurent78fedbf2023-03-09 14:40:44 +01004031 if (!areAllDevicesSupported(
4032 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004033 return BAD_VALUE;
4034 }
4035 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4036 if (status != NO_ERROR) {
4037 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4038 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4039 return status;
4040 }
4041
4042 checkForDeviceAndOutputChanges();
4043
4044 bool forceVolumeReeval = false;
4045 // TODO(b/263479999): workaround for truncated touch sounds
4046 // to be removed when the problem is handled by system UI
4047 uint32_t delayMs = 0;
4048 if (strategy == mCommunnicationStrategy) {
4049 forceVolumeReeval = true;
4050 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4051 updateInputRouting();
4052 }
4053 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4054
4055 return NO_ERROR;
4056}
4057
4058status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4059 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004060{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004061 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004062
Paul Wang5d7cdb52022-11-22 09:45:06 +00004063 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004064 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004065 ALOGW_IF(status != NAME_NOT_FOUND,
4066 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004067 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004068 return status;
4069 }
4070
4071 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004072
4073 bool forceVolumeReeval = false;
4074 // FIXME: workaround for truncated touch sounds
4075 // to be removed when the problem is handled by system UI
4076 uint32_t delayMs = 0;
4077 if (strategy == mCommunnicationStrategy) {
4078 forceVolumeReeval = true;
4079 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4080 updateInputRouting();
4081 }
4082 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004083
4084 return NO_ERROR;
4085}
4086
jiabin0a488932020-08-07 17:32:40 -07004087status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4088 device_role_t role,
4089 AudioDeviceTypeAddrVector &devices) {
4090 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004091}
4092
Jiabin Huang3b98d322020-09-03 17:54:16 +00004093status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4094 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4095 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4096 dumpAudioDeviceTypeAddrVector(devices).c_str());
4097
Mikhail Naganov55773032020-10-01 15:08:13 -07004098 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004099 return BAD_VALUE;
4100 }
4101 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4102 ALOGW_IF(status != NO_ERROR,
4103 "Engine could not set preferred devices %s for audio source %d role %d",
4104 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4105
4106 return status;
4107}
4108
4109status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4110 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4111 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4112 dumpAudioDeviceTypeAddrVector(devices).c_str());
4113
Mikhail Naganov55773032020-10-01 15:08:13 -07004114 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004115 return BAD_VALUE;
4116 }
4117 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4118 ALOGW_IF(status != NO_ERROR,
4119 "Engine could not add preferred devices %s for audio source %d role %d",
4120 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4121
Eric Laurent2517af32020-11-25 15:31:27 +01004122 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004123 return status;
4124}
4125
4126status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4127 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4128{
4129 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4130 dumpAudioDeviceTypeAddrVector(devices).c_str());
4131
Eric Laurent78fedbf2023-03-09 14:40:44 +01004132 if (!areAllDevicesSupported(
4133 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004134 return BAD_VALUE;
4135 }
4136
4137 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4138 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004139 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004140 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004141 if (status == NO_ERROR) {
4142 updateInputRouting();
4143 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004144 return status;
4145}
4146
4147status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4148 device_role_t role) {
4149 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4150
4151 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004152 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004153 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004154 if (status == NO_ERROR) {
4155 updateInputRouting();
4156 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004157 return status;
4158}
4159
4160status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4161 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4162 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4163}
4164
Oscar Azucena90e77632019-11-27 17:12:28 -08004165status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004166 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004167 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004168 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4169 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004170 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004171 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4172 if (status != NO_ERROR) {
4173 ALOGE("%s() could not set device affinity for userId %d",
4174 __FUNCTION__, userId);
4175 return status;
4176 }
4177
4178 // reevaluate outputs for all devices
4179 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004180 changeOutputDevicesMuteState(devices);
4181 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4182 true /* skipDelays */);
4183 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004184
4185 return NO_ERROR;
4186}
4187
4188status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004189 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004190 AudioDeviceTypeAddrVector devices;
4191 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004192 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4193 if (status != NO_ERROR) {
4194 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4195 __FUNCTION__, userId);
4196 return status;
4197 }
4198
4199 // reevaluate outputs for all devices
4200 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004201 changeOutputDevicesMuteState(devices);
4202 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4203 true /* skipDelays */);
4204 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004205
4206 return NO_ERROR;
4207}
4208
Andy Hungc29d82b2018-10-05 12:23:17 -07004209void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004210{
Andy Hungc29d82b2018-10-05 12:23:17 -07004211 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004212 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004213 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004214 std::string stateLiteral;
4215 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004216 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004217 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4218 "communications", "media", "record", "dock", "system",
4219 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4220 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4221 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004222 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4223 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4224 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4225 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4226 dst->append(" (MANUAL: ");
4227 dumpManualSurroundFormats(dst);
4228 dst->append(")");
4229 }
4230 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004231 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004232 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4233 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004234 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004235 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004236
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004237 dst->append("\n");
4238 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4239 dst->append("\n");
4240 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004241 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004242 mOutputs.dump(dst);
4243 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004244 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004245 mAudioPatches.dump(dst);
4246 mPolicyMixes.dump(dst);
4247 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004248
Kevin Rocardb99cc752019-03-21 20:52:24 -07004249 dst->appendFormat(" AllowedCapturePolicies:\n");
4250 for (auto& policy : mAllowedCapturePolicies) {
4251 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4252 }
4253
jiabina84c3d32022-12-02 18:59:55 +00004254 dst->appendFormat(" Preferred mixer audio configuration:\n");
4255 for (const auto it : mPreferredMixerAttrInfos) {
4256 dst->appendFormat(" - device port id: %d\n", it.first);
4257 for (const auto preferredMixerInfoIt : it.second) {
4258 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4259 preferredMixerInfoIt.second->dump(dst);
4260 }
4261 }
4262
François Gaffiec005e562018-11-06 15:04:49 +01004263 dst->appendFormat("\nPolicy Engine dump:\n");
4264 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004265}
4266
4267status_t AudioPolicyManager::dump(int fd)
4268{
4269 String8 result;
4270 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004271 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004272 return NO_ERROR;
4273}
4274
Kevin Rocardb99cc752019-03-21 20:52:24 -07004275status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4276{
4277 mAllowedCapturePolicies[uid] = capturePolicy;
4278 return NO_ERROR;
4279}
4280
Eric Laurente552edb2014-03-10 17:42:56 -07004281// This function checks for the parameters which can be offloaded.
4282// This can be enhanced depending on the capability of the DSP and policy
4283// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004284audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004285{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004286 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004287 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004288 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004289 offloadInfo.format,
4290 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4291 offloadInfo.has_video);
4292
jiabin2b9d5a12021-12-10 01:06:29 +00004293 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004294 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004295 }
4296
4297 // See if there is a profile to support this.
4298 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004299 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004300 offloadInfo.sample_rate,
4301 offloadInfo.format,
4302 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004303 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4304 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004305 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4306 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4307 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004308 if (profile == nullptr) {
4309 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4310 }
4311 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4312 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4313 }
4314 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004315}
4316
Michael Chana94fbb22018-04-24 14:31:19 +10004317bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4318 const audio_attributes_t& attributes) {
4319 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004320 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004321 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4322 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004323 config.sample_rate,
4324 config.format,
4325 config.channel_mask,
4326 output_flags,
4327 true /* directOnly */);
4328 ALOGV("%s() profile %sfound with name: %s, "
4329 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4330 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004331 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004332 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004333
4334 // also try the MSD module if compatible profile not found
4335 if (profile == nullptr) {
4336 profile = getMsdProfileForOutput(outputDevices,
4337 config.sample_rate,
4338 config.format,
4339 config.channel_mask,
4340 output_flags,
4341 true /* directOnly */);
4342 ALOGV("%s() MSD profile %sfound with name: %s, "
4343 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4344 __FUNCTION__, profile != 0 ? "" : "NOT ",
4345 (profile != 0 ? profile->getTagName().c_str() : "null"),
4346 config.sample_rate, config.format, config.channel_mask, output_flags);
4347 }
4348 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004349}
4350
jiabin2b9d5a12021-12-10 01:06:29 +00004351bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4352 bool durationIgnored) {
4353 if (mMasterMono) {
4354 return false; // no offloading if mono is set.
4355 }
4356
4357 // Check if offload has been disabled
4358 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4359 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4360 return false;
4361 }
4362
4363 // Check if stream type is music, then only allow offload as of now.
4364 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4365 {
4366 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4367 return false;
4368 }
4369
4370 //TODO: enable audio offloading with video when ready
4371 const bool allowOffloadWithVideo =
4372 property_get_bool("audio.offload.video", false /* default_value */);
4373 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4374 ALOGV("%s: has_video == true, returning false", __func__);
4375 return false;
4376 }
4377
4378 //If duration is less than minimum value defined in property, return false
4379 const int min_duration_secs = property_get_int32(
4380 "audio.offload.min.duration.secs", -1 /* default_value */);
4381 if (!durationIgnored) {
4382 if (min_duration_secs >= 0) {
4383 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4384 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4385 __func__, min_duration_secs);
4386 return false;
4387 }
4388 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4389 ALOGV("%s: Offload denied by duration < default min(=%u)",
4390 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4391 return false;
4392 }
4393 }
4394
4395 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4396 // creating an offloaded track and tearing it down immediately after start when audioflinger
4397 // detects there is an active non offloadable effect.
4398 // FIXME: We should check the audio session here but we do not have it in this context.
4399 // This may prevent offloading in rare situations where effects are left active by apps
4400 // in the background.
4401 if (mEffects.isNonOffloadableEffectEnabled()) {
4402 return false;
4403 }
4404
4405 return true;
4406}
4407
4408audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4409 const audio_config_t *config) {
4410 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4411 offloadInfo.format = config->format;
4412 offloadInfo.sample_rate = config->sample_rate;
4413 offloadInfo.channel_mask = config->channel_mask;
4414 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4415 offloadInfo.has_video = false;
4416 offloadInfo.is_streaming = false;
4417 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4418
4419 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4420 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4421 audio_flags_to_audio_output_flags(attr->flags, &flags);
4422 // only retain flags that will drive compressed offload or passthrough
4423 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4424 if (offloadPossible) {
4425 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4426 }
4427 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4428
Dorin Drimusfae3c642022-03-17 18:36:30 +01004429 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004430 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004431 DeviceVector outputDevices = engineOutputDevices;
4432 // the MSD module checks for different conditions and output devices
4433 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4434 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4435 continue;
4436 }
4437 outputDevices = getMsdAudioOutDevices();
4438 }
jiabin2b9d5a12021-12-10 01:06:29 +00004439 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004440 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004441 config->sample_rate, nullptr /*updatedSamplingRate*/,
4442 config->format, nullptr /*updatedFormat*/,
4443 config->channel_mask, nullptr /*updatedChannelMask*/,
4444 flags)) {
4445 continue;
4446 }
4447 // reject profiles not corresponding to a device currently available
4448 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4449 continue;
4450 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004451 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4452 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004453 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004454 != AUDIO_DIRECT_NOT_SUPPORTED) {
4455 // Already reports offload gapless supported. No need to report offload support.
4456 continue;
4457 }
4458 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4459 != AUDIO_OUTPUT_FLAG_NONE) {
4460 // If offload gapless is reported, no need to report offload support.
4461 directMode = (audio_direct_mode_t) ((directMode &
4462 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4463 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4464 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004465 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004466 }
4467 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004468 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004469 }
4470 }
4471 }
4472 return directMode;
4473}
4474
Dorin Drimusf2196d82022-01-03 12:11:18 +01004475status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4476 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004477 if (mEffects.isNonOffloadableEffectEnabled()) {
4478 return OK;
4479 }
jiabinf1c73972022-04-14 16:28:52 -07004480 DeviceVector devices;
4481 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004482 if (status != OK) {
4483 return status;
4484 }
4485 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4486 if (devices.empty()) {
4487 return OK; // no output devices for the attributes
4488 }
jiabinf1c73972022-04-14 16:28:52 -07004489 return getProfilesForDevices(devices, audioProfilesVector,
4490 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004491}
4492
jiabina84c3d32022-12-02 18:59:55 +00004493status_t AudioPolicyManager::getSupportedMixerAttributes(
4494 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4495 ALOGV("%s, portId=%d", __func__, portId);
4496 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4497 if (deviceDescriptor == nullptr) {
4498 ALOGE("%s the requested device is currently unavailable", __func__);
4499 return BAD_VALUE;
4500 }
jiabin96daffc2023-05-11 17:51:55 +00004501 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4502 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4503 deviceDescriptor->type());
4504 return BAD_VALUE;
4505 }
jiabina84c3d32022-12-02 18:59:55 +00004506 for (const auto& hwModule : mHwModules) {
4507 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4508 if (curProfile->supportsDevice(deviceDescriptor)) {
4509 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4510 }
4511 }
4512 }
4513 return NO_ERROR;
4514}
4515
4516status_t AudioPolicyManager::setPreferredMixerAttributes(
4517 const audio_attributes_t *attr,
4518 audio_port_handle_t portId,
4519 uid_t uid,
4520 const audio_mixer_attributes_t *mixerAttributes) {
4521 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4522 "mixerBehavior=%d}, uid=%d, portId=%u",
4523 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4524 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4525 mixerAttributes->mixer_behavior, uid, portId);
4526 if (attr->usage != AUDIO_USAGE_MEDIA) {
4527 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4528 return BAD_VALUE;
4529 }
4530 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4531 if (deviceDescriptor == nullptr) {
4532 ALOGE("%s the requested device is currently unavailable", __func__);
4533 return BAD_VALUE;
4534 }
4535 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4536 ALOGE("%s(%d), type=%d, is not a usb output device",
4537 __func__, portId, deviceDescriptor->type());
4538 return BAD_VALUE;
4539 }
4540
4541 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4542 audio_flags_to_audio_output_flags(attr->flags, &flags);
4543 flags = (audio_output_flags_t) (flags |
4544 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4545 sp<IOProfile> profile = nullptr;
4546 DeviceVector devices(deviceDescriptor);
4547 for (const auto& hwModule : mHwModules) {
4548 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4549 if (curProfile->hasDynamicAudioProfile()
4550 && curProfile->isCompatibleProfile(devices,
4551 mixerAttributes->config.sample_rate,
4552 nullptr /*updatedSamplingRate*/,
4553 mixerAttributes->config.format,
4554 nullptr /*updatedFormat*/,
4555 mixerAttributes->config.channel_mask,
4556 nullptr /*updatedChannelMask*/,
4557 flags,
4558 false /*exactMatchRequiredForInputFlags*/)) {
4559 profile = curProfile;
4560 break;
4561 }
4562 }
4563 }
4564 if (profile == nullptr) {
4565 ALOGE("%s, there is no compatible profile found", __func__);
4566 return BAD_VALUE;
4567 }
4568
4569 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4570 sp<PreferredMixerAttributesInfo>::make(
4571 uid, portId, profile, flags, *mixerAttributes);
4572 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4573 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4574
4575 // If 1) there is any client from the preferred mixer configuration owner that is currently
4576 // active and matches the strategy and 2) current output is on the preferred device and the
4577 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4578 // configuration.
4579 std::vector<audio_io_handle_t> outputsToReopen;
4580 for (size_t i = 0; i < mOutputs.size(); i++) {
4581 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004582 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4583 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4584 output->mUsePreferredMixerAttributes = true;
4585 } else {
4586 for (const auto &client: output->getActiveClients()) {
4587 if (client->uid() == uid && client->strategy() == strategy) {
4588 client->setIsInvalid();
4589 outputsToReopen.push_back(output->mIoHandle);
4590 }
jiabina84c3d32022-12-02 18:59:55 +00004591 }
4592 }
4593 }
4594 }
4595 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4596 config.sample_rate = mixerAttributes->config.sample_rate;
4597 config.channel_mask = mixerAttributes->config.channel_mask;
4598 config.format = mixerAttributes->config.format;
4599 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004600 sp<SwAudioOutputDescriptor> desc =
4601 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4602 if (desc == nullptr) {
4603 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4604 continue;
4605 }
4606 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004607 }
4608
4609 return NO_ERROR;
4610}
4611
4612sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004613 audio_port_handle_t devicePortId,
4614 product_strategy_t strategy,
4615 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004616 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4617 if (it == mPreferredMixerAttrInfos.end()) {
4618 return nullptr;
4619 }
jiabind9a58d32023-06-01 17:57:30 +00004620 if (activeBitPerfectPreferred) {
4621 for (auto [strategy, info] : it->second) {
4622 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4623 && info->getActiveClientCount() != 0) {
4624 return info;
4625 }
4626 }
jiabina84c3d32022-12-02 18:59:55 +00004627 }
jiabind9a58d32023-06-01 17:57:30 +00004628 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4629 return strategyMatchedMixerAttrInfoIt == it->second.end()
4630 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004631}
4632
4633status_t AudioPolicyManager::getPreferredMixerAttributes(
4634 const audio_attributes_t *attr,
4635 audio_port_handle_t portId,
4636 audio_mixer_attributes_t* mixerAttributes) {
4637 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4638 portId, mEngine->getProductStrategyForAttributes(*attr));
4639 if (info == nullptr) {
4640 return NAME_NOT_FOUND;
4641 }
4642 *mixerAttributes = info->getMixerAttributes();
4643 return NO_ERROR;
4644}
4645
4646status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4647 audio_port_handle_t portId,
4648 uid_t uid) {
4649 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4650 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4651 if (preferredMixerAttrInfo == nullptr) {
4652 return NAME_NOT_FOUND;
4653 }
4654 if (preferredMixerAttrInfo->getUid() != uid) {
4655 ALOGE("%s, requested uid=%d, owned uid=%d",
4656 __func__, uid, preferredMixerAttrInfo->getUid());
4657 return PERMISSION_DENIED;
4658 }
4659 mPreferredMixerAttrInfos[portId].erase(strategy);
4660 if (mPreferredMixerAttrInfos[portId].empty()) {
4661 mPreferredMixerAttrInfos.erase(portId);
4662 }
4663
4664 // Reconfig existing output
4665 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4666 for (size_t i = 0; i < mOutputs.size(); i++) {
4667 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4668 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4669 }
4670 }
4671 for (const auto output : potentialOutputsToReopen) {
4672 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4673 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4674 preferredMixerAttrInfo->getFlags())) {
4675 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4676 }
4677 }
4678 return NO_ERROR;
4679}
4680
Eric Laurent6a94d692014-05-20 11:18:06 -07004681status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4682 audio_port_type_t type,
4683 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004684 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004685 unsigned int *generation)
4686{
jiabin19cdba52020-11-24 11:28:58 -08004687 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4688 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004689 return BAD_VALUE;
4690 }
4691 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004692 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004693 *num_ports = 0;
4694 }
4695
4696 size_t portsWritten = 0;
4697 size_t portsMax = *num_ports;
4698 *num_ports = 0;
4699 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004700 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4701 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004702 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004703 for (const auto& dev : mAvailableOutputDevices) {
4704 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004705 continue;
4706 }
4707 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004708 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004709 }
4710 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004711 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004712 }
4713 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004714 for (const auto& dev : mAvailableInputDevices) {
4715 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004716 continue;
4717 }
4718 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004719 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004720 }
4721 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004722 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004723 }
4724 }
4725 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4726 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4727 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4728 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4729 }
4730 *num_ports += mInputs.size();
4731 }
4732 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004733 size_t numOutputs = 0;
4734 for (size_t i = 0; i < mOutputs.size(); i++) {
4735 if (!mOutputs[i]->isDuplicated()) {
4736 numOutputs++;
4737 if (portsWritten < portsMax) {
4738 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4739 }
4740 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004741 }
Eric Laurent84c70242014-06-23 08:46:27 -07004742 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004743 }
4744 }
jiabina84c3d32022-12-02 18:59:55 +00004745
Eric Laurent6a94d692014-05-20 11:18:06 -07004746 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004747 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004748 return NO_ERROR;
4749}
4750
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004751status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4752 std::vector<media::AudioPortFw>* _aidl_return) {
4753 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4754 audio_port_v7 port;
4755 dev->toAudioPort(&port);
4756 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4757 _aidl_return->push_back(std::move(aidlPort));
4758 return OK;
4759 };
4760
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004761 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004762 for (const auto& dev : module->getDeclaredDevices()) {
4763 if (role == media::AudioPortRole::NONE ||
4764 ((role == media::AudioPortRole::SOURCE)
4765 == audio_is_input_device(dev->type()))) {
4766 RETURN_STATUS_IF_ERROR(pushPort(dev));
4767 }
4768 }
4769 }
4770 return OK;
4771}
4772
jiabin19cdba52020-11-24 11:28:58 -08004773status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004774{
Eric Laurent99fcae42018-05-17 16:59:18 -07004775 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4776 return BAD_VALUE;
4777 }
4778 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4779 if (dev != 0) {
4780 dev->toAudioPort(port);
4781 return NO_ERROR;
4782 }
4783 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4784 if (dev != 0) {
4785 dev->toAudioPort(port);
4786 return NO_ERROR;
4787 }
4788 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4789 if (out != 0) {
4790 out->toAudioPort(port);
4791 return NO_ERROR;
4792 }
4793 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4794 if (in != 0) {
4795 in->toAudioPort(port);
4796 return NO_ERROR;
4797 }
4798 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004799}
4800
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004801status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4802 audio_patch_handle_t *handle,
4803 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004804{
François Gaffieafd4cea2019-11-18 15:50:22 +01004805 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004806 if (handle == NULL || patch == NULL) {
4807 return BAD_VALUE;
4808 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004809 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004810 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004811 return BAD_VALUE;
4812 }
4813 // only one source per audio patch supported for now
4814 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004815 return INVALID_OPERATION;
4816 }
Eric Laurent874c42872014-08-08 15:13:39 -07004817 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004818 return INVALID_OPERATION;
4819 }
Eric Laurent874c42872014-08-08 15:13:39 -07004820 for (size_t i = 0; i < patch->num_sinks; i++) {
4821 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4822 return INVALID_OPERATION;
4823 }
4824 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004825
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004826 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4827 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4828 if (srcDevice == nullptr || sinkDevice == nullptr) {
4829 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4830 return BAD_VALUE;
4831 }
4832 ALOGV("%s between source %s and sink %s", __func__,
4833 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4834 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4835 // Default attributes, default volume priority, not to infer with non raw audio patches.
4836 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4837 const struct audio_port_config *source = &patch->sources[0];
4838 sp<SourceClientDescriptor> sourceDesc =
4839 new InternalSourceClientDescriptor(
4840 portId, uid, attributes, *source, srcDevice, sinkDevice,
4841 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4842
4843 status_t status =
4844 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4845
4846 if (status != NO_ERROR) {
4847 return INVALID_OPERATION;
4848 }
4849 mAudioSources.add(portId, sourceDesc);
4850 return NO_ERROR;
4851}
4852
4853status_t AudioPolicyManager::connectAudioSourceToSink(
4854 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4855 const struct audio_patch *patch,
4856 audio_patch_handle_t &handle,
4857 uid_t uid, uint32_t delayMs)
4858{
4859 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4860 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4861 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4862 return INVALID_OPERATION;
4863 }
4864 sourceDesc->connect(handle, sinkDevice);
4865 if (isMsdPatch(handle)) {
4866 return NO_ERROR;
4867 }
4868 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4869 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4870 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4871 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4872 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4873 goto FailurePatchAdded;
4874 }
4875 status = swOutput->start();
4876 if (status != NO_ERROR) {
4877 goto FailureSourceAdded;
4878 }
4879 swOutput->addClient(sourceDesc);
4880 status = startSource(swOutput, sourceDesc, &delayMs);
4881 if (status != NO_ERROR) {
4882 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4883 goto FailureSourceActive;
4884 }
4885 if (delayMs != 0) {
4886 usleep(delayMs * 1000);
4887 }
4888 return NO_ERROR;
4889
4890FailureSourceActive:
4891 swOutput->stop();
4892 releaseOutput(sourceDesc->portId());
4893FailureSourceAdded:
4894 sourceDesc->setSwOutput(nullptr);
4895FailurePatchAdded:
4896 releaseAudioPatchInternal(handle);
4897 return INVALID_OPERATION;
4898}
4899
4900status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4901 audio_patch_handle_t *handle,
4902 uid_t uid, uint32_t delayMs,
4903 const sp<SourceClientDescriptor>& sourceDesc)
4904{
4905 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004906 sp<AudioPatch> patchDesc;
4907 ssize_t index = mAudioPatches.indexOfKey(*handle);
4908
François Gaffieafd4cea2019-11-18 15:50:22 +01004909 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4910 patch->sources[0].role,
4911 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004912#if LOG_NDEBUG == 0
4913 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004914 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4915 patch->sinks[i].role,
4916 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004917 }
4918#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004919
4920 if (index >= 0) {
4921 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004922 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4923 __func__, mUidCached, patchDesc->getUid(), uid);
4924 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004925 return INVALID_OPERATION;
4926 }
4927 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004928 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004929 }
4930
4931 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004932 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004933 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004934 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004935 return BAD_VALUE;
4936 }
Eric Laurent84c70242014-06-23 08:46:27 -07004937 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4938 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004939 if (patchDesc != 0) {
4940 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004941 ALOGV("%s source id differs for patch current id %d new id %d",
4942 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004943 return BAD_VALUE;
4944 }
4945 }
Eric Laurent874c42872014-08-08 15:13:39 -07004946 DeviceVector devices;
4947 for (size_t i = 0; i < patch->num_sinks; i++) {
4948 // Only support mix to devices connection
4949 // TODO add support for mix to mix connection
4950 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004951 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004952 return INVALID_OPERATION;
4953 }
4954 sp<DeviceDescriptor> devDesc =
4955 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4956 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004957 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004958 return BAD_VALUE;
4959 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004960
François Gaffie11d30102018-11-02 16:09:09 +01004961 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004962 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004963 NULL, // updatedSamplingRate
4964 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004965 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004966 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004967 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004968 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004969 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004970 return INVALID_OPERATION;
4971 }
4972 devices.add(devDesc);
4973 }
4974 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004975 return INVALID_OPERATION;
4976 }
Eric Laurent874c42872014-08-08 15:13:39 -07004977
Eric Laurent6a94d692014-05-20 11:18:06 -07004978 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004979 ALOGV("%s setting device %s on output %d",
4980 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304981 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004982 index = mAudioPatches.indexOfKey(*handle);
4983 if (index >= 0) {
4984 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004985 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004986 }
4987 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004988 patchDesc->setUid(uid);
4989 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004990 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004991 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004992 return INVALID_OPERATION;
4993 }
4994 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4995 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4996 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004997 // only one sink supported when connecting an input device to a mix
4998 if (patch->num_sinks > 1) {
4999 return INVALID_OPERATION;
5000 }
François Gaffie53615e22015-03-19 09:24:12 +01005001 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005002 if (inputDesc == NULL) {
5003 return BAD_VALUE;
5004 }
5005 if (patchDesc != 0) {
5006 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5007 return BAD_VALUE;
5008 }
5009 }
François Gaffie11d30102018-11-02 16:09:09 +01005010 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005011 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005012 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005013 return BAD_VALUE;
5014 }
5015
François Gaffie11d30102018-11-02 16:09:09 +01005016 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08005017 patch->sinks[0].sample_rate,
5018 NULL, /*updatedSampleRate*/
5019 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005020 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005021 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005022 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005023 // FIXME for the parameter type,
5024 // and the NONE
5025 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005026 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005027 return INVALID_OPERATION;
5028 }
5029 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005030 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005031 device->toString().c_str(), inputDesc->mIoHandle);
5032 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005033 index = mAudioPatches.indexOfKey(*handle);
5034 if (index >= 0) {
5035 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005036 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005037 }
5038 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005039 patchDesc->setUid(uid);
5040 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005041 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005042 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005043 return INVALID_OPERATION;
5044 }
5045 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5046 // device to device connection
5047 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005048 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005049 return BAD_VALUE;
5050 }
5051 }
François Gaffie11d30102018-11-02 16:09:09 +01005052 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005053 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005054 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005055 return BAD_VALUE;
5056 }
Eric Laurent874c42872014-08-08 15:13:39 -07005057
Eric Laurent6a94d692014-05-20 11:18:06 -07005058 //update source and sink with our own data as the data passed in the patch may
5059 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005060 PatchBuilder patchBuilder;
5061 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005062
5063 // if first sink is to MSD, establish single MSD patch
5064 if (getMsdAudioOutDevices().contains(
5065 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5066 ALOGV("%s patching to MSD", __FUNCTION__);
5067 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5068 goto installPatch;
5069 }
5070
François Gaffieafd4cea2019-11-18 15:50:22 +01005071 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5072 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005073
Eric Laurent874c42872014-08-08 15:13:39 -07005074 for (size_t i = 0; i < patch->num_sinks; i++) {
5075 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005076 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005077 return INVALID_OPERATION;
5078 }
François Gaffie11d30102018-11-02 16:09:09 +01005079 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005080 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005081 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005082 return BAD_VALUE;
5083 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005084 audio_port_config sinkPortConfig = {};
5085 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5086 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005087
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005088 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5089 // volume management purpose (tracking activity)
5090 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5091 // in config XML to reach the sink so that is can be declared as available.
5092 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005093 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005094 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005095 // take care of dynamic routing for SwOutput selection,
5096 audio_attributes_t attributes = sourceDesc->attributes();
5097 audio_stream_type_t stream = sourceDesc->stream();
5098 audio_attributes_t resultAttr;
5099 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5100 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005101 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5102 config.channel_mask =
5103 (audio_channel_mask_get_representation(sourceMask)
5104 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5105 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005106 config.format = sourceDesc->config().format;
5107 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5108 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5109 bool isRequestedDeviceForExclusiveUse = false;
5110 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005111 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005112 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005113 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5114 &stream, sourceDesc->uid(), &config, &flags,
5115 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005116 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005117 if (output == AUDIO_IO_HANDLE_NONE) {
5118 ALOGV("%s no output for device %s",
5119 __FUNCTION__, sinkDevice->toString().c_str());
5120 return INVALID_OPERATION;
5121 }
5122 outputDesc = mOutputs.valueFor(output);
5123 if (outputDesc->isDuplicated()) {
5124 ALOGE("%s output is duplicated", __func__);
5125 return INVALID_OPERATION;
5126 }
François Gaffie7e39df22022-04-26 12:48:49 +02005127 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5128 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005129 } else {
5130 // Same for "raw patches" aka created from createAudioPatch API
5131 SortedVector<audio_io_handle_t> outputs =
5132 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5133 // if the sink device is reachable via an opened output stream, request to
5134 // go via this output stream by adding a second source to the patch
5135 // description
5136 output = selectOutput(outputs);
5137 if (output == AUDIO_IO_HANDLE_NONE) {
5138 ALOGE("%s no output available for internal patch sink", __func__);
5139 return INVALID_OPERATION;
5140 }
5141 outputDesc = mOutputs.valueFor(output);
5142 if (outputDesc->isDuplicated()) {
5143 ALOGV("%s output for device %s is duplicated",
5144 __func__, sinkDevice->toString().c_str());
5145 return INVALID_OPERATION;
5146 }
François Gaffie7e39df22022-04-26 12:48:49 +02005147 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005148 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005149 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005150 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005151 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005152 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005153 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5154 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005155 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5156 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005157 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005158 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005159 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005160 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005161 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005162 return INVALID_OPERATION;
5163 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005164 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005165 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005166 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005167 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005168 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005169 srcMixPortConfig.ext.mix.usecase.stream =
5170 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005171 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5172 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005173 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005174 }
Eric Laurent83b88082014-06-20 18:31:16 -07005175 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005176 }
5177 // TODO: check from routing capabilities in config file and other conflicting patches
5178
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005179installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005180 status_t status = installPatch(
5181 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005182 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005183 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005184 return INVALID_OPERATION;
5185 }
5186 } else {
5187 return BAD_VALUE;
5188 }
5189 } else {
5190 return BAD_VALUE;
5191 }
5192 return NO_ERROR;
5193}
5194
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005195status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005196{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005197 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005198 ssize_t index = mAudioPatches.indexOfKey(handle);
5199
5200 if (index < 0) {
5201 return BAD_VALUE;
5202 }
5203 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005204 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5205 __func__, mUidCached, patchDesc->getUid(), uid);
5206 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005207 return INVALID_OPERATION;
5208 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005209 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5210 for (size_t i = 0; i < mAudioSources.size(); i++) {
5211 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5212 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5213 portId = sourceDesc->portId();
5214 break;
5215 }
5216 }
5217 return portId != AUDIO_PORT_HANDLE_NONE ?
5218 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005219}
Eric Laurent6a94d692014-05-20 11:18:06 -07005220
François Gaffieafd4cea2019-11-18 15:50:22 +01005221status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005222 uint32_t delayMs,
5223 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005224{
5225 ALOGV("%s patch %d", __func__, handle);
5226 if (mAudioPatches.indexOfKey(handle) < 0) {
5227 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5228 return BAD_VALUE;
5229 }
5230 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005231 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005232 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005233 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005234 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005235 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005236 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005237 return BAD_VALUE;
5238 }
5239
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305240 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005241 getNewOutputDevices(outputDesc, true /*fromCache*/),
5242 true,
5243 0,
5244 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005245 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5246 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005247 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005248 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005249 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005250 return BAD_VALUE;
5251 }
5252 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005253 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005254 true,
5255 NULL);
5256 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005257 status_t status =
5258 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5259 ALOGV("%s patch panel returned %d patchHandle %d",
5260 __func__, status, patchDesc->getAfHandle());
5261 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005262 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005263 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005264 // SW or HW Bridge
5265 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5266 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005267 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005268 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5269 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5270 outputDesc = sourceDesc->swOutput().promote();
5271 }
5272 if (outputDesc == nullptr) {
5273 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5274 // releaseOutput has already called closeOutput in case of direct output
5275 return NO_ERROR;
5276 }
François Gaffie7e39df22022-04-26 12:48:49 +02005277 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005278 // While using a HwBridge, force reconsidering device only if not reusing an existing
5279 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005280 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005281 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5282 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5283 // Reconsider device only for cases:
5284 // 1 / Active Output
5285 // 2 / Inactive Output previously hosting HwBridge
5286 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5287 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5288 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305289 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005290 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5291 outputDesc->devices(),
5292 force,
5293 0,
5294 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005295 } else {
5296 return BAD_VALUE;
5297 }
5298 } else {
5299 return BAD_VALUE;
5300 }
5301 return NO_ERROR;
5302}
5303
5304status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5305 struct audio_patch *patches,
5306 unsigned int *generation)
5307{
François Gaffie53615e22015-03-19 09:24:12 +01005308 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005309 return BAD_VALUE;
5310 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005311 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005312 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005313}
5314
Eric Laurente1715a42014-05-20 11:30:42 -07005315status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005316{
Eric Laurente1715a42014-05-20 11:30:42 -07005317 ALOGV("setAudioPortConfig()");
5318
5319 if (config == NULL) {
5320 return BAD_VALUE;
5321 }
5322 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5323 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005324 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5325 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005326 }
5327
Eric Laurenta121f902014-06-03 13:32:54 -07005328 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005329 if (config->type == AUDIO_PORT_TYPE_MIX) {
5330 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005331 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005332 if (outputDesc == NULL) {
5333 return BAD_VALUE;
5334 }
Eric Laurent84c70242014-06-23 08:46:27 -07005335 ALOG_ASSERT(!outputDesc->isDuplicated(),
5336 "setAudioPortConfig() called on duplicated output %d",
5337 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005338 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005339 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005340 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005341 if (inputDesc == NULL) {
5342 return BAD_VALUE;
5343 }
Eric Laurenta121f902014-06-03 13:32:54 -07005344 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005345 } else {
5346 return BAD_VALUE;
5347 }
5348 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5349 sp<DeviceDescriptor> deviceDesc;
5350 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5351 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5352 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5353 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5354 } else {
5355 return BAD_VALUE;
5356 }
5357 if (deviceDesc == NULL) {
5358 return BAD_VALUE;
5359 }
Eric Laurenta121f902014-06-03 13:32:54 -07005360 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005361 } else {
5362 return BAD_VALUE;
5363 }
5364
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005365 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005366 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5367 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005368 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005369 audioPortConfig->toAudioPortConfig(&newConfig, config);
5370 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005371 }
Eric Laurenta121f902014-06-03 13:32:54 -07005372 if (status != NO_ERROR) {
5373 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005374 }
Eric Laurente1715a42014-05-20 11:30:42 -07005375
5376 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005377}
5378
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005379void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5380{
Eric Laurentd60560a2015-04-10 11:31:20 -07005381 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005382 clearAudioPatches(uid);
5383 clearSessionRoutes(uid);
5384}
5385
Eric Laurent6a94d692014-05-20 11:18:06 -07005386void AudioPolicyManager::clearAudioPatches(uid_t uid)
5387{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005388 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005389 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005390 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005391 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005392 }
5393 }
5394}
5395
François Gaffiec005e562018-11-06 15:04:49 +01005396void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005397{
François Gaffiec005e562018-11-06 15:04:49 +01005398 // Take the first attributes following the product strategy as it is used to retrieve the routed
5399 // device. All attributes wihin a strategy follows the same "routing strategy"
5400 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5401 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005402 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005403 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005404 for (size_t j = 0; j < mOutputs.size(); j++) {
5405 if (mOutputs.keyAt(j) == ouptutToSkip) {
5406 continue;
5407 }
5408 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005409 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005410 continue;
5411 }
5412 // If the default device for this strategy is on another output mix,
5413 // invalidate all tracks in this strategy to force re connection.
5414 // Otherwise select new device on the output mix.
5415 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005416 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005417 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005418 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5419 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5420 // If the device is using preferred mixer attributes, the output need to reopen
5421 // with default configuration when the new selected devices are different from
5422 // current routing devices.
5423 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5424 continue;
5425 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305426 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005427 }
5428 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005429 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005430}
5431
5432void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5433{
5434 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005435 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005436 for (size_t i = 0; i < mOutputs.size(); i++) {
5437 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005438 for (const auto& client : outputDesc->getClientIterable()) {
5439 if (client->hasPreferredDevice() && client->uid() == uid) {
5440 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005441 auto clientStrategy = client->strategy();
5442 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5443 end(affectedStrategies)) {
5444 continue;
5445 }
5446 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005447 }
5448 }
5449 }
5450 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005451 for (const auto& strategy : affectedStrategies) {
5452 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005453 }
5454
5455 // remove input routes associated with this uid
5456 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005457 for (size_t i = 0; i < mInputs.size(); i++) {
5458 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005459 for (const auto& client : inputDesc->getClientIterable()) {
5460 if (client->hasPreferredDevice() && client->uid() == uid) {
5461 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5462 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005463 }
5464 }
5465 }
5466 // reroute inputs if necessary
5467 SortedVector<audio_io_handle_t> inputsToClose;
5468 for (size_t i = 0; i < mInputs.size(); i++) {
5469 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005470 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005471 inputsToClose.add(inputDesc->mIoHandle);
5472 }
5473 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005474 for (const auto& input : inputsToClose) {
5475 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005476 }
5477}
5478
Eric Laurentd60560a2015-04-10 11:31:20 -07005479void AudioPolicyManager::clearAudioSources(uid_t uid)
5480{
5481 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005482 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5483 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005484 stopAudioSource(mAudioSources.keyAt(i));
5485 }
5486 }
5487}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005488
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005489status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5490 audio_io_handle_t *ioHandle,
5491 audio_devices_t *device)
5492{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005493 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5494 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005495 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005496 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5497 if (deviceDesc == nullptr) {
5498 return INVALID_OPERATION;
5499 }
5500 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005501
François Gaffiedf372692015-03-19 10:43:27 +01005502 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005503}
5504
Eric Laurentd60560a2015-04-10 11:31:20 -07005505status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005506 const audio_attributes_t *attributes,
5507 audio_port_handle_t *portId,
5508 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005509{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005510 ALOGV("%s", __FUNCTION__);
5511 *portId = AUDIO_PORT_HANDLE_NONE;
5512
5513 if (source == NULL || attributes == NULL || portId == NULL) {
5514 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5515 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005516 return BAD_VALUE;
5517 }
5518
Eric Laurentd60560a2015-04-10 11:31:20 -07005519 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5520 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005521 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5522 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005523 return INVALID_OPERATION;
5524 }
5525
François Gaffie11d30102018-11-02 16:09:09 +01005526 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005527 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005528 String8(source->ext.device.address),
5529 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005530 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005531 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005532 return BAD_VALUE;
5533 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005534
jiabin4ef93452019-09-10 14:29:54 -07005535 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005536
François Gaffieaaac0fd2018-11-22 17:56:39 +01005537 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005538 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005539 mEngine->getStreamTypeForAttributes(*attributes),
5540 mEngine->getProductStrategyForAttributes(*attributes),
5541 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005542
5543 status_t status = connectAudioSource(sourceDesc);
5544 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005545 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005546 }
5547 return status;
5548}
5549
Francois Gaffie601801d2021-06-22 13:27:39 +02005550sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5551 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5552{
5553 ALOGV("%s", __FUNCTION__);
5554 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5555
5556 status_t status = startAudioSource(source, attributes, &portId, uid);
5557 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5558 return mAudioSources.valueFor(portId);
5559}
5560
5561
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005562status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005563{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005564 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005565
5566 // make sure we only have one patch per source.
5567 disconnectAudioSource(sourceDesc);
5568
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005569 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005570 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5571 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5572 sourceDesc->srcDevice()->type(),
5573 String8(sourceDesc->srcDevice()->address().c_str()),
5574 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005575 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005576 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005577 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005578 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005579 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5580 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5581 return INVALID_OPERATION;
5582 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005583 PatchBuilder patchBuilder;
5584 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5585 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005586
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005587 return connectAudioSourceToSink(
5588 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005589}
5590
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005591status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005592{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005593 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5594 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005595 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005596 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005597 return BAD_VALUE;
5598 }
5599 status_t status = disconnectAudioSource(sourceDesc);
5600
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005601 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005602 return status;
5603}
5604
Andy Hung2ddee192015-12-18 17:34:44 -08005605status_t AudioPolicyManager::setMasterMono(bool mono)
5606{
5607 if (mMasterMono == mono) {
5608 return NO_ERROR;
5609 }
5610 mMasterMono = mono;
5611 // if enabling mono we close all offloaded devices, which will invalidate the
5612 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5613 // for recreating the new AudioTrack as non-offloaded PCM.
5614 //
5615 // If disabling mono, we leave all tracks as is: we don't know which clients
5616 // and tracks are able to be recreated as offloaded. The next "song" should
5617 // play back offloaded.
5618 if (mMasterMono) {
5619 Vector<audio_io_handle_t> offloaded;
5620 for (size_t i = 0; i < mOutputs.size(); ++i) {
5621 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5622 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5623 offloaded.push(desc->mIoHandle);
5624 }
5625 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005626 for (const auto& handle : offloaded) {
5627 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005628 }
5629 }
5630 // update master mono for all remaining outputs
5631 for (size_t i = 0; i < mOutputs.size(); ++i) {
5632 updateMono(mOutputs.keyAt(i));
5633 }
5634 return NO_ERROR;
5635}
5636
5637status_t AudioPolicyManager::getMasterMono(bool *mono)
5638{
5639 *mono = mMasterMono;
5640 return NO_ERROR;
5641}
5642
Eric Laurentac9cef52017-06-09 15:46:26 -07005643float AudioPolicyManager::getStreamVolumeDB(
5644 audio_stream_type_t stream, int index, audio_devices_t device)
5645{
jiabin9a3361e2019-10-01 09:38:30 -07005646 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005647}
5648
jiabin81772902018-04-02 17:52:27 -07005649status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5650 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005651 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005652{
Kriti Dang6537def2021-03-02 13:46:59 +01005653 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5654 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005655 return BAD_VALUE;
5656 }
Kriti Dang6537def2021-03-02 13:46:59 +01005657 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5658 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005659
5660 size_t formatsWritten = 0;
5661 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005662
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005663 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005664 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5665 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005666 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005667 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005668 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005669 bool formatEnabled = true;
5670 switch (forceUse) {
5671 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005672 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005673 break;
5674 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5675 formatEnabled = false;
5676 break;
5677 default: // AUTO or ALWAYS => true
5678 break;
jiabin81772902018-04-02 17:52:27 -07005679 }
5680 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5681 }
jiabin81772902018-04-02 17:52:27 -07005682 }
5683 return NO_ERROR;
5684}
5685
Kriti Dang6537def2021-03-02 13:46:59 +01005686status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5687 audio_format_t *surroundFormats) {
5688 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5689 return BAD_VALUE;
5690 }
5691 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5692 __func__, *numSurroundFormats, surroundFormats);
5693
5694 size_t formatsWritten = 0;
5695 size_t formatsMax = *numSurroundFormats;
5696 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5697
5698 // Return formats from all device profiles that have already been resolved by
5699 // checkOutputsForDevice().
5700 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5701 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5702 audio_devices_t deviceType = device->type();
5703 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5704 // returns formats reported by HDMI devices.
5705 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5706 continue;
5707 }
5708 // Formats reported by sink devices
5709 std::unordered_set<audio_format_t> formatset;
5710 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5711 formatset.insert(it->second.begin(), it->second.end());
5712 }
5713
5714 // Formats hard-coded in the in policy configuration file (if any).
5715 FormatVector encodedFormats = device->encodedFormats();
5716 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5717 // Filter the formats which are supported by the vendor hardware.
5718 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005719 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005720 formats.insert(*it);
5721 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005722 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005723 if (pair.second.count(*it) != 0) {
5724 formats.insert(pair.first);
5725 break;
5726 }
5727 }
5728 }
5729 }
5730 }
5731 *numSurroundFormats = formats.size();
5732 for (const auto& format: formats) {
5733 if (formatsWritten < formatsMax) {
5734 surroundFormats[formatsWritten++] = format;
5735 }
5736 }
5737 return NO_ERROR;
5738}
5739
jiabin81772902018-04-02 17:52:27 -07005740status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5741{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005742 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005743 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5744 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005745 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005746 return BAD_VALUE;
5747 }
5748
Mikhail Naganov100f0122018-11-29 11:22:16 -08005749 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5750 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005751 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005752 return INVALID_OPERATION;
5753 }
5754
Mikhail Naganov100f0122018-11-29 11:22:16 -08005755 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005756 return NO_ERROR;
5757 }
5758
Mikhail Naganov100f0122018-11-29 11:22:16 -08005759 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005760 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005761 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005762 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005763 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005764 }
5765 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005766 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005767 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005768 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005769 }
5770 }
5771
5772 sp<SwAudioOutputDescriptor> outputDesc;
5773 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005774 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5775 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005776 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5777 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005778 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005779 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005780 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5781 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5782 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005783 name.c_str(),
5784 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005785 if (status != NO_ERROR) {
5786 continue;
5787 }
5788 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5789 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5790 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005791 name.c_str(),
5792 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005793 profileUpdated |= (status == NO_ERROR);
5794 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005795 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005796 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005797 AUDIO_DEVICE_IN_HDMI);
5798 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5799 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005800 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005801 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005802 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5803 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5804 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005805 name.c_str(),
5806 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005807 if (status != NO_ERROR) {
5808 continue;
5809 }
5810 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5811 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5812 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005813 name.c_str(),
5814 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005815 profileUpdated |= (status == NO_ERROR);
5816 }
5817
jiabin81772902018-04-02 17:52:27 -07005818 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005819 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005820 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005821 }
5822
5823 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5824}
5825
Eric Laurent5ada82e2019-08-29 17:53:54 -07005826void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005827{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005828 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005829 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005830 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005831 }
5832}
5833
jiabin6012f912018-11-02 17:06:30 -07005834bool AudioPolicyManager::isHapticPlaybackSupported()
5835{
5836 for (const auto& hwModule : mHwModules) {
5837 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5838 for (const auto &outProfile : outputProfiles) {
5839 struct audio_port audioPort;
5840 outProfile->toAudioPort(&audioPort);
5841 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5842 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5843 return true;
5844 }
5845 }
5846 }
5847 }
5848 return false;
5849}
5850
Carter Hsu325a8eb2022-01-19 19:56:51 +08005851bool AudioPolicyManager::isUltrasoundSupported()
5852{
5853 bool hasUltrasoundOutput = false;
5854 bool hasUltrasoundInput = false;
5855 for (const auto& hwModule : mHwModules) {
5856 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5857 if (!hasUltrasoundOutput) {
5858 for (const auto &outProfile : outputProfiles) {
5859 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5860 hasUltrasoundOutput = true;
5861 break;
5862 }
5863 }
5864 }
5865
5866 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5867 if (!hasUltrasoundInput) {
5868 for (const auto &inputProfile : inputProfiles) {
5869 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5870 hasUltrasoundInput = true;
5871 break;
5872 }
5873 }
5874 }
5875
5876 if (hasUltrasoundOutput && hasUltrasoundInput)
5877 return true;
5878 }
5879 return false;
5880}
5881
Atneya Nair698f5ef2022-12-15 16:15:09 -08005882bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5883{
5884 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5885 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5886 for (const auto& hwModule : mHwModules) {
5887 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5888 for (const auto &inputProfile : inputProfiles) {
5889 if ((inputProfile->getFlags() & mask) == mask) {
5890 return true;
5891 }
5892 }
5893 }
5894 return false;
5895}
5896
Eric Laurent8340e672019-11-06 11:01:08 -08005897bool AudioPolicyManager::isCallScreenModeSupported()
5898{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005899 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005900}
5901
5902
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005903status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005904{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005905 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005906 if (!sourceDesc->isConnected()) {
5907 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5908 return NO_ERROR;
5909 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005910 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5911 if (swOutput != 0) {
5912 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005913 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005914 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005915 }
jiabinbce0c1d2020-10-05 11:20:18 -07005916 if (releaseOutput(sourceDesc->portId())) {
5917 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5918 // no need to release audio patch here but just return NO_ERROR.
5919 return NO_ERROR;
5920 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005921 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005922 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005923 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005924 // close Hwoutput and remove from mHwOutputs
5925 } else {
5926 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5927 }
5928 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005929 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005930 sourceDesc->disconnect();
5931 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005932}
5933
François Gaffiec005e562018-11-06 15:04:49 +01005934sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5935 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005936{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005937 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005938 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005939 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005940 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005941 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5942 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005943 source = sourceDesc;
5944 break;
5945 }
5946 }
5947 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005948}
5949
Eric Laurentb4f42a92022-01-17 17:37:31 +01005950bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005951 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005952 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005953{
5954 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5955 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005956 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005957 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005958 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5959 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5960 return false;
5961 }
5962 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5963 return false;
5964 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005965 }
5966
Eric Laurentd332bc82023-08-04 11:45:23 +02005967 // The caller can have the audio config criteria ignored by either passing a null ptr or
5968 // the AUDIO_CONFIG_INITIALIZER value.
5969 // If an audio config is specified, current policy is to only allow spatialization for
5970 // some positional channel masks and PCM format
5971
5972 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
5973 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
5974 return false;
5975 }
5976 if (!audio_is_linear_pcm(config->format)) {
5977 return false;
5978 }
5979 }
5980
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005981 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005982 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005983 if (profile == nullptr) {
5984 return false;
5985 }
5986
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005987 return true;
5988}
5989
5990void AudioPolicyManager::checkVirtualizerClientRoutes() {
5991 std::set<audio_stream_type_t> streamsToInvalidate;
5992 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005993 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5994 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005995 audio_attributes_t attr = client->attributes();
5996 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5997 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5998 audio_config_base_t clientConfig = client->config();
5999 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006000 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006001 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006002 streamsToInvalidate.insert(client->stream());
6003 }
6004 }
6005 }
6006
jiabinc44b3462022-12-08 12:52:31 -08006007 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006008}
6009
Eric Laurente191d1b2022-04-15 11:59:25 +02006010
6011bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6012 const sp<SwAudioOutputDescriptor>& outputDesc) {
6013 if (outputDesc->isDuplicated()) {
6014 return false;
6015 }
6016 DeviceVector devices = outputDesc->supportedDevices();
6017 for (size_t i = 0; i < mOutputs.size(); i++) {
6018 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6019 if (desc == outputDesc || desc->isDuplicated()) {
6020 continue;
6021 }
6022 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6023 if (!sharedDevices.isEmpty()
6024 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6025 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6026 return false;
6027 }
6028 }
6029 return true;
6030}
6031
6032
Eric Laurentfa0f6742021-08-17 18:39:44 +02006033status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006034 const audio_attributes_t *attr,
6035 audio_io_handle_t *output) {
6036 *output = AUDIO_IO_HANDLE_NONE;
6037
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006038 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6039 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6040 audio_config_t *configPtr = nullptr;
6041 audio_config_t config;
6042 if (mixerConfig != nullptr) {
6043 config = audio_config_initializer(mixerConfig);
6044 configPtr = &config;
6045 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006046 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006047 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006048 return BAD_VALUE;
6049 }
6050
6051 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006052 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006053 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006054 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006055 return BAD_VALUE;
6056 }
6057
Eric Laurente191d1b2022-04-15 11:59:25 +02006058 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006059 for (size_t i = 0; i < mOutputs.size(); i++) {
6060 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006061 if (!desc->isDuplicated()
6062 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6063 spatializerOutputs.push_back(desc);
6064 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006065 }
6066 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006067 mSpatializerOutput.clear();
6068 bool outputsChanged = false;
6069 for (const auto& desc : spatializerOutputs) {
6070 if (desc->mProfile == profile
6071 && (configPtr == nullptr
6072 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6073 mSpatializerOutput = desc;
6074 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6075 } else {
6076 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6077 " and devices %s", __func__, desc->mIoHandle,
6078 configPtr != nullptr ? configPtr->channel_mask : 0,
6079 devices.toString().c_str());
6080 closeOutput(desc->mIoHandle);
6081 outputsChanged = true;
6082 }
Eric Laurent39095982021-08-24 18:29:27 +02006083 }
6084
Eric Laurente191d1b2022-04-15 11:59:25 +02006085 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006086 sp<SwAudioOutputDescriptor> desc =
6087 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006088 if (desc != nullptr) {
6089 mSpatializerOutput = desc;
6090 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006091 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006092 }
6093
6094 checkVirtualizerClientRoutes();
6095
Eric Laurente191d1b2022-04-15 11:59:25 +02006096 if (outputsChanged) {
6097 mPreviousOutputs = mOutputs;
6098 mpClientInterface->onAudioPortListUpdate();
6099 }
6100
6101 if (mSpatializerOutput == nullptr) {
6102 ALOGV("%s could not open spatializer output with requested config", __func__);
6103 return BAD_VALUE;
6104 }
Eric Laurent39095982021-08-24 18:29:27 +02006105 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006106 ALOGV("%s returning new spatializer output %d", __func__, *output);
6107 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006108}
6109
Eric Laurentfa0f6742021-08-17 18:39:44 +02006110status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6111 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006112 return INVALID_OPERATION;
6113 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006114 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006115 return BAD_VALUE;
6116 }
Eric Laurent39095982021-08-24 18:29:27 +02006117
Eric Laurente191d1b2022-04-15 11:59:25 +02006118 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6119 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6120 closeOutput(mSpatializerOutput->mIoHandle);
6121 //from now on mSpatializerOutput is null
6122 checkVirtualizerClientRoutes();
6123 }
Eric Laurent39095982021-08-24 18:29:27 +02006124
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006125 return NO_ERROR;
6126}
6127
Eric Laurente552edb2014-03-10 17:42:56 -07006128// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006129// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006130// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006131uint32_t AudioPolicyManager::nextAudioPortGeneration()
6132{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006133 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006134}
6135
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006136AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006137 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006138 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006139 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006140 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006141 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006142 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006143 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006144 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006145 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006146 mAudioPortGeneration(1),
6147 mBeaconMuteRefCount(0),
6148 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006149 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006150 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006151 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006152 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006153{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006154}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006155
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006156status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006157 if (mEngine == nullptr) {
6158 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006159 }
6160 mEngine->setObserver(this);
6161 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006162 if (status != NO_ERROR) {
6163 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6164 return status;
6165 }
François Gaffie2110e042015-03-24 08:41:51 +01006166
jiabin29230182023-04-04 21:02:36 +00006167 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6168 // at the end of this function.
6169 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006170 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6171 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6172
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006173 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006174 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006175 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006176
Eric Laurent3a4311c2014-03-17 12:00:47 -07006177 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006178 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6179 defaultOutputDevice == nullptr ||
6180 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6181 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6182 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006183 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006184 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006185 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006186
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006187 // Silence ALOGV statements
6188 property_set("log.tag." LOG_TAG, "D");
6189
Eric Laurente552edb2014-03-10 17:42:56 -07006190 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006191 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006192}
6193
Eric Laurente0720872014-03-11 09:30:41 -07006194AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006195{
Eric Laurente552edb2014-03-10 17:42:56 -07006196 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006197 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006198 }
6199 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006200 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006201 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006202 mAvailableOutputDevices.clear();
6203 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006204 mOutputs.clear();
6205 mInputs.clear();
6206 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006207 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006208 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006209}
6210
Eric Laurente0720872014-03-11 09:30:41 -07006211status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006212{
Eric Laurent87ffa392015-05-22 10:32:38 -07006213 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006214}
6215
Eric Laurente552edb2014-03-10 17:42:56 -07006216// ---
6217
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006218void AudioPolicyManager::onNewAudioModulesAvailable()
6219{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006220 DeviceVector newDevices;
6221 onNewAudioModulesAvailableInt(&newDevices);
6222 if (!newDevices.empty()) {
6223 nextAudioPortGeneration();
6224 mpClientInterface->onAudioPortListUpdate();
6225 }
6226}
6227
6228void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6229{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006230 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006231 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6232 continue;
6233 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006234 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006235 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6236 handle != AUDIO_MODULE_HANDLE_NONE) {
6237 hwModule->setHandle(handle);
6238 } else {
6239 ALOGW("could not load HW module %s", hwModule->getName());
6240 continue;
6241 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006242 }
6243 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006244 // open all output streams needed to access attached devices.
6245 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006246 // This also validates mAvailableOutputDevices list
6247 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6248 if (!outProfile->canOpenNewIo()) {
6249 ALOGE("Invalid Output profile max open count %u for profile %s",
6250 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6251 continue;
6252 }
6253 if (!outProfile->hasSupportedDevices()) {
6254 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6255 continue;
6256 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006257 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6258 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006259 mTtsOutputAvailable = true;
6260 }
6261
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006262 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006263 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006264 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006265 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6266 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006267 } else {
6268 // choose first device present in profile's SupportedDevices also part of
6269 // mAvailableOutputDevices.
6270 if (availProfileDevices.isEmpty()) {
6271 continue;
6272 }
6273 supportedDevice = availProfileDevices.itemAt(0);
6274 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006275 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006276 continue;
6277 }
6278 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6279 mpClientInterface);
6280 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006281 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6282 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006283 AUDIO_STREAM_DEFAULT,
6284 AUDIO_OUTPUT_FLAG_NONE, &output);
6285 if (status != NO_ERROR) {
6286 ALOGW("Cannot open output stream for devices %s on hw module %s",
6287 supportedDevice->toString().c_str(), hwModule->getName());
6288 continue;
6289 }
6290 for (const auto &device : availProfileDevices) {
6291 // give a valid ID to an attached device once confirmed it is reachable
6292 if (!device->isAttached()) {
6293 device->attach(hwModule);
6294 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006295 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006296 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006297 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6298 }
6299 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006300 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006301 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6302 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006303 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006304 }
Eric Laurent39095982021-08-24 18:29:27 +02006305 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006306 outputDesc->close();
6307 } else {
6308 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306309 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006310 DeviceVector(supportedDevice),
6311 true,
6312 0,
6313 NULL);
6314 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006315 }
6316 // open input streams needed to access attached devices to validate
6317 // mAvailableInputDevices list
6318 for (const auto& inProfile : hwModule->getInputProfiles()) {
6319 if (!inProfile->canOpenNewIo()) {
6320 ALOGE("Invalid Input profile max open count %u for profile %s",
6321 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6322 continue;
6323 }
6324 if (!inProfile->hasSupportedDevices()) {
6325 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6326 continue;
6327 }
6328 // chose first device present in profile's SupportedDevices also part of
6329 // available input devices
6330 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006331 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006332 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006333 ALOGV("%s: Input device list is empty! for profile %s",
6334 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006335 continue;
6336 }
6337 sp<AudioInputDescriptor> inputDesc =
6338 new AudioInputDescriptor(inProfile, mpClientInterface);
6339
6340 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6341 status_t status = inputDesc->open(nullptr,
6342 availProfileDevices.itemAt(0),
6343 AUDIO_SOURCE_MIC,
6344 AUDIO_INPUT_FLAG_NONE,
6345 &input);
6346 if (status != NO_ERROR) {
6347 ALOGW("Cannot open input stream for device %s on hw module %s",
6348 availProfileDevices.toString().c_str(),
6349 hwModule->getName());
6350 continue;
6351 }
6352 for (const auto &device : availProfileDevices) {
6353 // give a valid ID to an attached device once confirmed it is reachable
6354 if (!device->isAttached()) {
6355 device->attach(hwModule);
6356 device->importAudioPortAndPickAudioProfile(inProfile, true);
6357 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006358 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006359 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6360 }
6361 }
6362 inputDesc->close();
6363 }
6364 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006365
6366 // Check if spatializer outputs can be closed until used.
6367 // mOutputs vector never contains duplicated outputs at this point.
6368 std::vector<audio_io_handle_t> outputsClosed;
6369 for (size_t i = 0; i < mOutputs.size(); i++) {
6370 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6371 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6372 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6373 outputsClosed.push_back(desc->mIoHandle);
6374 desc->close();
6375 }
6376 }
6377 for (auto output : outputsClosed) {
6378 removeOutput(output);
6379 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006380}
6381
Eric Laurent98e38192018-02-15 18:31:53 -08006382void AudioPolicyManager::addOutput(audio_io_handle_t output,
6383 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006384{
Eric Laurent1c333e22014-05-20 10:48:17 -07006385 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006386 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006387 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006388 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006389 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006390}
6391
François Gaffie53615e22015-03-19 09:24:12 +01006392void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6393{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006394 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6395 ALOGV("%s: removing primary output", __func__);
6396 mPrimaryOutput = nullptr;
6397 }
François Gaffie53615e22015-03-19 09:24:12 +01006398 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006399 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006400}
6401
Eric Laurent98e38192018-02-15 18:31:53 -08006402void AudioPolicyManager::addInput(audio_io_handle_t input,
6403 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006404{
Eric Laurent1c333e22014-05-20 10:48:17 -07006405 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006406 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006407}
Eric Laurente552edb2014-03-10 17:42:56 -07006408
François Gaffie11d30102018-11-02 16:09:09 +01006409status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006410 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006411 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006412{
François Gaffie11d30102018-11-02 16:09:09 +01006413 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006414 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006415 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006416
François Gaffie11d30102018-11-02 16:09:09 +01006417 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006418 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006419 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006420 }
Eric Laurente552edb2014-03-10 17:42:56 -07006421
Eric Laurent3b73df72014-03-11 09:06:29 -07006422 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006423 // first call getAudioPort to get the supported attributes from the HAL
6424 struct audio_port_v7 port = {};
6425 device->toAudioPort(&port);
6426 status_t status = mpClientInterface->getAudioPort(&port);
6427 if (status == NO_ERROR) {
6428 device->importAudioPort(port);
6429 }
6430
6431 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006432 for (size_t i = 0; i < mOutputs.size(); i++) {
6433 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006434 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006435 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006436 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6437 mOutputs.keyAt(i), device->toString().c_str());
6438 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006439 }
6440 }
6441 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006442 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006443 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006444 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6445 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006446 if (profile->supportsDevice(device)) {
6447 profiles.add(profile);
6448 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6449 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006450 }
6451 }
6452 }
6453
Eric Laurent7b279bb2015-12-14 10:18:23 -08006454 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006455
Eric Laurente552edb2014-03-10 17:42:56 -07006456 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006457 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006458 return BAD_VALUE;
6459 }
6460
6461 // open outputs for matching profiles if needed. Direct outputs are also opened to
6462 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6463 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006464 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006465
6466 // nothing to do if one output is already opened for this profile
6467 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006468 for (j = 0; j < outputs.size(); j++) {
6469 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006470 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006471 // matching profile: save the sample rates, format and channel masks supported
6472 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006473 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006474 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006475 }
Eric Laurente552edb2014-03-10 17:42:56 -07006476 break;
6477 }
6478 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006479 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006480 continue;
6481 }
6482
Eric Laurent3974e3b2017-12-07 17:58:43 -08006483 if (!profile->canOpenNewIo()) {
6484 ALOGW("Max Output number %u already opened for this profile %s",
6485 profile->maxOpenCount, profile->getTagName().c_str());
6486 continue;
6487 }
6488
Eric Laurent83efe1c2017-07-09 16:51:08 -07006489 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006490 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006491 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6492 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006493 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006494 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006495 profiles.removeAt(profile_index);
6496 profile_index--;
6497 } else {
6498 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006499 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006500 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006501 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6502 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006503 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006504 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006505
François Gaffie11d30102018-11-02 16:09:09 +01006506 if (device_distinguishes_on_address(deviceType)) {
6507 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6508 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306509 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6510 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006511 }
Eric Laurente552edb2014-03-10 17:42:56 -07006512 ALOGV("checkOutputsForDevice(): adding output %d", output);
6513 }
6514 }
6515
6516 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006517 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006518 return BAD_VALUE;
6519 }
Eric Laurentd4692962014-05-05 18:13:44 -07006520 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006521 // check if one opened output is not needed any more after disconnecting one device
6522 for (size_t i = 0; i < mOutputs.size(); i++) {
6523 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006524 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006525 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006526 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006527 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006528 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006529 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006530 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6531 mOutputs.keyAt(i));
6532 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006533 }
Eric Laurente552edb2014-03-10 17:42:56 -07006534 }
6535 }
Eric Laurentd4692962014-05-05 18:13:44 -07006536 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006537 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006538 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6539 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006540 if (!profile->supportsDevice(device)) {
6541 continue;
6542 }
6543 ALOGV("checkOutputsForDevice(): "
6544 "clearing direct output profile %zu on module %s",
6545 j, hwModule->getName());
6546 profile->clearAudioProfiles();
6547 if (!profile->hasDynamicAudioProfile()) {
6548 continue;
6549 }
6550 // When a device is disconnected, if there is an IOProfile that contains dynamic
6551 // profiles and supports the disconnected device, call getAudioPort to repopulate
6552 // the capabilities of the devices that is supported by the IOProfile.
6553 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6554 if (supportedDevice == device ||
6555 !mAvailableOutputDevices.contains(supportedDevice)) {
6556 continue;
6557 }
6558 struct audio_port_v7 port;
6559 supportedDevice->toAudioPort(&port);
6560 status_t status = mpClientInterface->getAudioPort(&port);
6561 if (status == NO_ERROR) {
6562 supportedDevice->importAudioPort(port);
6563 }
Eric Laurente552edb2014-03-10 17:42:56 -07006564 }
6565 }
6566 }
6567 }
6568 return NO_ERROR;
6569}
6570
François Gaffie11d30102018-11-02 16:09:09 +01006571status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006572 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006573{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006574 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006575
François Gaffie11d30102018-11-02 16:09:09 +01006576 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006577 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006578 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006579 }
6580
Eric Laurentd4692962014-05-05 18:13:44 -07006581 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006582 // first call getAudioPort to get the supported attributes from the HAL
6583 struct audio_port_v7 port = {};
6584 device->toAudioPort(&port);
6585 status_t status = mpClientInterface->getAudioPort(&port);
6586 if (status == NO_ERROR) {
6587 device->importAudioPort(port);
6588 }
6589
Eric Laurent0dd51852019-04-19 18:18:58 -07006590 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006591 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006592 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006593 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006594 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006595 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006596 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006597
François Gaffie11d30102018-11-02 16:09:09 +01006598 if (profile->supportsDevice(device)) {
6599 profiles.add(profile);
6600 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6601 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006602 }
6603 }
6604 }
6605
Eric Laurent0dd51852019-04-19 18:18:58 -07006606 if (profiles.isEmpty()) {
6607 ALOGW("%s: No input profile available for device %s",
6608 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006609 return BAD_VALUE;
6610 }
6611
6612 // open inputs for matching profiles if needed. Direct inputs are also opened to
6613 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6614 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6615
Eric Laurent1c333e22014-05-20 10:48:17 -07006616 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006617
Eric Laurentd4692962014-05-05 18:13:44 -07006618 // nothing to do if one input is already opened for this profile
6619 size_t input_index;
6620 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6621 desc = mInputs.valueAt(input_index);
6622 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006623 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006624 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006625 }
Eric Laurentd4692962014-05-05 18:13:44 -07006626 break;
6627 }
6628 }
6629 if (input_index != mInputs.size()) {
6630 continue;
6631 }
6632
Eric Laurent3974e3b2017-12-07 17:58:43 -08006633 if (!profile->canOpenNewIo()) {
6634 ALOGW("Max Input number %u already opened for this profile %s",
6635 profile->maxOpenCount, profile->getTagName().c_str());
6636 continue;
6637 }
6638
Eric Laurentfe231122017-11-17 17:48:06 -08006639 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006640 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006641 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006642
Eric Laurentcf2c0212014-07-25 16:20:43 -07006643 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006644 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006645 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006646 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006647 mpClientInterface->setParameters(input, String8(param));
6648 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006649 }
jiabin12537fc2023-10-12 17:56:08 +00006650 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006651 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006652 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006653 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006654 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006655 }
6656
Eric Laurent0dd51852019-04-19 18:18:58 -07006657 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006658 addInput(input, desc);
6659 }
6660 } // endif input != 0
6661
Eric Laurentcf2c0212014-07-25 16:20:43 -07006662 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006663 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006664 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006665 profiles.removeAt(profile_index);
6666 profile_index--;
6667 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006668 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006669 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006670 }
Eric Laurentd4692962014-05-05 18:13:44 -07006671 ALOGV("checkInputsForDevice(): adding input %d", input);
6672 }
6673 } // end scan profiles
6674
6675 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006676 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006677 return BAD_VALUE;
6678 }
6679 } else {
6680 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006681 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006682 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006683 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006684 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006685 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006686 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006687 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006688 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6689 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006690 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006691 }
6692 }
6693 }
6694 } // end disconnect
6695
6696 return NO_ERROR;
6697}
6698
6699
Eric Laurente0720872014-03-11 09:30:41 -07006700void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006701{
6702 ALOGV("closeOutput(%d)", output);
6703
François Gaffie1c878552018-11-22 16:53:21 +01006704 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6705 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006706 ALOGW("closeOutput() unknown output %d", output);
6707 return;
6708 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006709 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006710 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006711
Eric Laurente552edb2014-03-10 17:42:56 -07006712 // look for duplicated outputs connected to the output being removed.
6713 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006714 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6715 if (dupOutput->isDuplicated() &&
6716 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6717 sp<SwAudioOutputDescriptor> remainingOutput =
6718 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006719 // As all active tracks on duplicated output will be deleted,
6720 // and as they were also referenced on the other output, the reference
6721 // count for their stream type must be adjusted accordingly on
6722 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006723 const bool wasActive = remainingOutput->isActive();
6724 // Note: no-op on the closing output where all clients has already been set inactive
6725 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006726 // stop() will be a no op if the output is still active but is needed in case all
6727 // active streams refcounts where cleared above
6728 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006729 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006730 }
Eric Laurente552edb2014-03-10 17:42:56 -07006731 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6732 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6733
6734 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006735 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006736 }
6737 }
6738
Eric Laurent05b90f82014-08-27 15:32:29 -07006739 nextAudioPortGeneration();
6740
François Gaffie1c878552018-11-22 16:53:21 +01006741 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006742 if (index >= 0) {
6743 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006744 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6745 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006746 mAudioPatches.removeItemsAt(index);
6747 mpClientInterface->onAudioPatchListUpdate();
6748 }
6749
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006750 if (closingOutputWasActive) {
6751 closingOutput->stop();
6752 }
François Gaffie1c878552018-11-22 16:53:21 +01006753 closingOutput->close();
jiabin14b50cc2023-12-13 19:01:52 +00006754 if ((closingOutput->getFlags().output & AUDIO_OUTPUT_FLAG_BIT_PERFECT)
6755 == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
6756 for (const auto device : closingOutput->devices()) {
6757 device->setPreferredConfig(nullptr);
6758 }
6759 }
Eric Laurente552edb2014-03-10 17:42:56 -07006760
François Gaffie53615e22015-03-19 09:24:12 +01006761 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006762 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006763 if (closingOutput == mSpatializerOutput) {
6764 mSpatializerOutput.clear();
6765 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006766
6767 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6768 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006769 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006770 bool directOutputOpen = false;
6771 for (size_t i = 0; i < mOutputs.size(); i++) {
6772 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6773 directOutputOpen = true;
6774 break;
6775 }
6776 }
6777 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006778 ALOGV("no direct outputs open, reset MSD patches");
6779 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6780 // how output devices for patching are resolved. Avoid by caching and reusing the
6781 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6782 // devices to patch to. This may be complicated by the fact that devices may become
6783 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006784 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006785 }
6786 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006787}
6788
6789void AudioPolicyManager::closeInput(audio_io_handle_t input)
6790{
6791 ALOGV("closeInput(%d)", input);
6792
6793 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6794 if (inputDesc == NULL) {
6795 ALOGW("closeInput() unknown input %d", input);
6796 return;
6797 }
6798
Eric Laurent6a94d692014-05-20 11:18:06 -07006799 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006800
François Gaffie11d30102018-11-02 16:09:09 +01006801 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006802 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006803 if (index >= 0) {
6804 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006805 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6806 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006807 mAudioPatches.removeItemsAt(index);
6808 mpClientInterface->onAudioPatchListUpdate();
6809 }
6810
François Gaffie6ebbce02023-07-19 13:27:53 +02006811 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006812 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006813 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006814
François Gaffie11d30102018-11-02 16:09:09 +01006815 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6816 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006817 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006818 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006819 }
Eric Laurente552edb2014-03-10 17:42:56 -07006820}
6821
François Gaffie11d30102018-11-02 16:09:09 +01006822SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6823 const DeviceVector &devices,
6824 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006825{
6826 SortedVector<audio_io_handle_t> outputs;
6827
François Gaffie11d30102018-11-02 16:09:09 +01006828 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006829 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006830 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006831 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006832 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006833 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006834 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006835 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006836 outputs.add(openOutputs.keyAt(i));
6837 }
6838 }
6839 return outputs;
6840}
6841
Mikhail Naganov37977152018-07-11 15:54:44 -07006842void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6843{
6844 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6845 // output is suspended before any tracks are moved to it
6846 checkA2dpSuspend();
6847 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006848 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006849 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006850 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006851 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006852 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6853 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6854 // configuration changes will ultimately be rerouted correctly. We can still avoid
6855 // unnecessary rerouting by caching and reusing the arguments to
6856 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6857 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006858 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006859 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006860 // an event that changed routing likely occurred, inform upper layers
6861 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006862}
6863
François Gaffiec005e562018-11-06 15:04:49 +01006864bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6865 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006866{
François Gaffiec005e562018-11-06 15:04:49 +01006867 return mEngine->getProductStrategyForAttributes(lAttr) ==
6868 mEngine->getProductStrategyForAttributes(rAttr);
6869}
6870
Francois Gaffieff1eb522020-05-06 18:37:04 +02006871void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6872{
6873 for (size_t i = 0; i < mAudioSources.size(); i++) {
6874 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6875 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006876 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006877 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006878 connectAudioSource(sourceDesc);
6879 }
6880 }
6881}
6882
6883void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6884{
6885 for (size_t i = 0; i < mAudioSources.size(); i++) {
6886 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6887 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6888 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6889 disconnectAudioSource(sourceDesc);
6890 }
6891 }
6892}
6893
François Gaffiec005e562018-11-06 15:04:49 +01006894void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6895{
6896 auto psId = mEngine->getProductStrategyForAttributes(attr);
6897
6898 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6899 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006900
François Gaffie11d30102018-11-02 16:09:09 +01006901 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6902 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006903
Eric Laurentc209fe42020-06-05 18:11:23 -07006904 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006905 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006906 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006907 // take into account dynamic audio policies related changes: if a client is now associated
6908 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006909 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006910 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6911 if (desc->isDuplicated()) {
6912 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006913 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006914 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6915 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6916 continue;
6917 }
6918 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006919 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006920 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6921 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6922 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006923 if (status != OK) {
6924 continue;
6925 }
yucliuf4de36d2020-09-14 14:57:56 -07006926 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006927 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006928 maxLatency = desc->latency();
6929 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006930 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006931 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006932 }
6933 }
6934
Eric Laurent56ed8842022-11-15 16:04:41 +01006935 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006936 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6937 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006938 for (audio_io_handle_t srcOut : srcOutputs) {
6939 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006940 if (desc == nullptr) continue;
6941
6942 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006943 maxLatency = desc->latency();
6944 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006945
Eric Laurent56ed8842022-11-15 16:04:41 +01006946 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006947 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006948 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006949 // a client on a non direct outputs has necessarily a linear PCM format
6950 // so we can call selectOutput() safely
6951 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6952 client->flags(),
6953 client->config().format,
6954 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006955 client->config().sample_rate,
6956 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006957 if (newOutput != srcOut) {
6958 invalidate = true;
6959 break;
6960 }
6961 } else {
6962 sp<IOProfile> profile = getProfileForOutput(newDevices,
6963 client->config().sample_rate,
6964 client->config().format,
6965 client->config().channel_mask,
6966 client->flags(),
6967 true /* directOnly */);
6968 if (profile != desc->mProfile) {
6969 invalidate = true;
6970 break;
6971 }
6972 }
6973 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006974 // mute strategy while moving tracks from one output to another
6975 if (invalidate) {
6976 invalidatedOutputs.push_back(desc);
6977 if (desc->isStrategyActive(psId)) {
6978 setStrategyMute(psId, true, desc);
6979 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6980 newDevices.types());
6981 }
Eric Laurente552edb2014-03-10 17:42:56 -07006982 }
François Gaffiec005e562018-11-06 15:04:49 +01006983 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006984 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006985 connectAudioSource(source);
6986 }
Eric Laurente552edb2014-03-10 17:42:56 -07006987 }
6988
Eric Laurent56ed8842022-11-15 16:04:41 +01006989 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6990 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6991 std::to_string(srcOutputs[0]).c_str(),
6992 std::to_string(dstOutputs[0]).c_str());
6993
François Gaffiec005e562018-11-06 15:04:49 +01006994 // Move effects associated to this stream from previous output to new output
6995 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006996 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006997 }
François Gaffiec005e562018-11-06 15:04:49 +01006998 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006999 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007000 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007001 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007002 desc->setTracksInvalidatedStatusByStrategy(psId);
7003 }
Eric Laurente552edb2014-03-10 17:42:56 -07007004 }
7005 }
7006}
7007
Eric Laurente0720872014-03-11 09:30:41 -07007008void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007009{
François Gaffiec005e562018-11-06 15:04:49 +01007010 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7011 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7012 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007013 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007014 }
Eric Laurente552edb2014-03-10 17:42:56 -07007015}
7016
Kevin Rocard153f92d2018-12-18 18:33:28 -08007017void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007018 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007019 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007020 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007021 for (size_t i = 0; i < mOutputs.size(); i++) {
7022 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7023 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007024 sp<AudioPolicyMix> primaryMix;
7025 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007026 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007027 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7028 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7029 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007030 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7031 for (auto &secondaryMix : secondaryMixes) {
7032 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7033 if (outputDesc != nullptr &&
7034 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7035 secondaryDescs.push_back(outputDesc);
7036 }
7037 }
7038
jiabinc44b3462022-12-08 12:52:31 -08007039 if (status != OK &&
7040 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7041 // When it failed to query secondary output, only invalidate the client that is not
7042 // MMAP. The reason is that MMAP stream will not support secondary output.
7043 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007044 } else if (!std::equal(
7045 client->getSecondaryOutputs().begin(),
7046 client->getSecondaryOutputs().end(),
7047 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007048 if (!audio_is_linear_pcm(client->config().format)) {
7049 // If the format is not PCM, the tracks should be invalidated to get correct
7050 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007051 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007052 } else {
7053 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7054 std::vector<audio_io_handle_t> secondaryOutputIds;
7055 for (const auto &secondaryDesc: secondaryDescs) {
7056 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7057 weakSecondaryDescs.push_back(secondaryDesc);
7058 }
7059 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7060 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007061 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007062 }
7063 }
7064 }
jiabin10a03f12021-05-07 23:46:28 +00007065 if (!trackSecondaryOutputs.empty()) {
7066 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7067 }
jiabinc44b3462022-12-08 12:52:31 -08007068 if (!clientsToInvalidate.empty()) {
7069 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7070 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007071 }
7072}
7073
Eric Laurent2517af32020-11-25 15:31:27 +01007074bool AudioPolicyManager::isScoRequestedForComm() const {
7075 AudioDeviceTypeAddrVector devices;
7076 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7077 for (const auto &device : devices) {
7078 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7079 return true;
7080 }
7081 }
7082 return false;
7083}
7084
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007085bool AudioPolicyManager::isHearingAidUsedForComm() const {
7086 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7087 true /*fromCache*/);
7088 for (const auto &device : devices) {
7089 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7090 return true;
7091 }
7092 }
7093 return false;
7094}
7095
7096
Eric Laurente0720872014-03-11 09:30:41 -07007097void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007098{
François Gaffie53615e22015-03-19 09:24:12 +01007099 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007100 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007101 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007102 return;
7103 }
7104
Eric Laurent3a4311c2014-03-17 12:00:47 -07007105 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007106 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7107 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007108 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007109
7110 // if suspended, restore A2DP output if:
7111 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007112 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007113 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007114 //
Eric Laurentf732e072016-08-03 19:30:28 -07007115 // if not suspended, suspend A2DP output if:
7116 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007117 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007118 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007119 //
7120 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007121 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007122 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007123 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007124 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007125
7126 mpClientInterface->restoreOutput(a2dpOutput);
7127 mA2dpSuspended = false;
7128 }
7129 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007130 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007131 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007132 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007133 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007134
7135 mpClientInterface->suspendOutput(a2dpOutput);
7136 mA2dpSuspended = true;
7137 }
7138 }
7139}
7140
François Gaffie11d30102018-11-02 16:09:09 +01007141DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7142 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007143{
François Gaffiedb1755b2023-09-01 11:50:35 +02007144 if (outputDesc == nullptr) {
7145 return DeviceVector{};
7146 }
François Gaffie11d30102018-11-02 16:09:09 +01007147
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007148 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007149 if (index >= 0) {
7150 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007151 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007152 ALOGV("%s device %s forced by patch %d", __func__,
7153 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7154 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007155 }
7156 }
7157
Dean Wheatley514b4312020-06-17 21:45:00 +10007158 // Do not retrieve engine device for outputs through MSD
7159 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7160 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7161 return outputDesc->devices();
7162 }
7163
Eric Laurent97ac8712018-07-27 18:59:02 -07007164 // Honor explicit routing requests only if no client using default routing is active on this
7165 // input: a specific app can not force routing for other apps by setting a preferred device.
7166 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007167 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007168 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007169 if (device != nullptr) {
7170 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007171 }
7172
François Gaffiea807ef92018-11-05 10:44:33 +01007173 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7174 // of setForceUse / Default Bus device here
7175 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7176 if (device != nullptr) {
7177 return DeviceVector(device);
7178 }
7179
François Gaffiedb1755b2023-09-01 11:50:35 +02007180 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007181 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7182 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7183 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307184 auto hasStreamActive = [&](auto stream) {
7185 return hasStream(streams, stream) && isStreamActive(stream, 0);
7186 };
Eric Laurent484e9272018-06-07 17:29:23 -07007187
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307188 auto doGetOutputDevicesForVoice = [&]() {
7189 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007190 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307191 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007192 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7193 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307194 };
7195
7196 // With low-latency playing on speaker, music on WFD, when the first low-latency
7197 // output is stopped, getNewOutputDevices checks for a product strategy
7198 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007199 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307200 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7201 // stream is associated to the output descriptor.
7202 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7203 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7204 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7205 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007206 // Retrieval of devices for voice DL is done on primary output profile, cannot
7207 // check the route (would force modifying configuration file for this profile)
7208 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7209 break;
7210 }
Eric Laurente552edb2014-03-10 17:42:56 -07007211 }
François Gaffiec005e562018-11-06 15:04:49 +01007212 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007213 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007214}
7215
François Gaffie11d30102018-11-02 16:09:09 +01007216sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7217 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007218{
François Gaffie11d30102018-11-02 16:09:09 +01007219 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007220
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007221 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007222 if (index >= 0) {
7223 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007224 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007225 ALOGV("getNewInputDevice() device %s forced by patch %d",
7226 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7227 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007228 }
7229 }
7230
Eric Laurent97ac8712018-07-27 18:59:02 -07007231 // Honor explicit routing requests only if no client using default routing is active on this
7232 // input: a specific app can not force routing for other apps by setting a preferred device.
7233 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007234 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7235 if (device != nullptr) {
7236 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007237 }
7238
Eric Laurentdc95a252018-04-12 12:46:56 -07007239 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007240 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007241 audio_attributes_t attributes;
7242 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007243 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007244 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7245 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007246 attributes = topClient->attributes();
7247 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007248 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007249 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007250 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7251 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007252 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007253 }
7254
Francois Gaffie716e1432019-01-14 16:58:59 +01007255 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7256 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007257 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007258 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007259 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007260 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007261
Eric Laurente552edb2014-03-10 17:42:56 -07007262 return device;
7263}
7264
Eric Laurent794fde22016-03-11 09:50:45 -08007265bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7266 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007267 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007268}
7269
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007270status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007271 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007272 if (devices == nullptr) {
7273 return BAD_VALUE;
7274 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007275
Andy Hung6d23c0f2022-02-16 09:37:15 -08007276 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007277 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7278 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007279 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007280 for (const auto& device : curDevices) {
7281 devices->push_back(device->getDeviceTypeAddr());
7282 }
7283 return NO_ERROR;
7284}
7285
Eric Laurente0720872014-03-11 09:30:41 -07007286void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007287 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007288 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007289 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007290 updateDevicesAndOutputs();
7291 break;
7292 default:
7293 break;
7294 }
7295}
7296
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007297uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007298
7299 // skip beacon mute management if a dedicated TTS output is available
7300 if (mTtsOutputAvailable) {
7301 return 0;
7302 }
7303
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007304 switch(event) {
7305 case STARTING_OUTPUT:
7306 mBeaconMuteRefCount++;
7307 break;
7308 case STOPPING_OUTPUT:
7309 if (mBeaconMuteRefCount > 0) {
7310 mBeaconMuteRefCount--;
7311 }
7312 break;
7313 case STARTING_BEACON:
7314 mBeaconPlayingRefCount++;
7315 break;
7316 case STOPPING_BEACON:
7317 if (mBeaconPlayingRefCount > 0) {
7318 mBeaconPlayingRefCount--;
7319 }
7320 break;
7321 }
7322
7323 if (mBeaconMuteRefCount > 0) {
7324 // any playback causes beacon to be muted
7325 return setBeaconMute(true);
7326 } else {
7327 // no other playback: unmute when beacon starts playing, mute when it stops
7328 return setBeaconMute(mBeaconPlayingRefCount == 0);
7329 }
7330}
7331
7332uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7333 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7334 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7335 // keep track of muted state to avoid repeating mute/unmute operations
7336 if (mBeaconMuted != mute) {
7337 // mute/unmute AUDIO_STREAM_TTS on all outputs
7338 ALOGV("\t muting %d", mute);
7339 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007340 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7341 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7342 ALOGV("\t no tts volume source available");
7343 return 0;
7344 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007345 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007346 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007347 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007348 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007349 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007350 maxLatency = latency;
7351 }
7352 }
7353 mBeaconMuted = mute;
7354 return maxLatency;
7355 }
7356 return 0;
7357}
7358
Eric Laurente0720872014-03-11 09:30:41 -07007359void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007360{
François Gaffiec005e562018-11-06 15:04:49 +01007361 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007362 mPreviousOutputs = mOutputs;
7363}
7364
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007365uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007366 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007367 uint32_t delayMs)
7368{
7369 // mute/unmute strategies using an incompatible device combination
7370 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7371 // if unmuting, unmute only after the specified delay
7372 if (outputDesc->isDuplicated()) {
7373 return 0;
7374 }
7375
7376 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007377 DeviceVector devices = outputDesc->devices();
7378 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007379
François Gaffiec005e562018-11-06 15:04:49 +01007380 auto productStrategies = mEngine->getOrderedProductStrategies();
7381 for (const auto &productStrategy : productStrategies) {
7382 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7383 DeviceVector curDevices =
7384 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7385 curDevices = curDevices.filter(outputDesc->supportedDevices());
7386 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007387 bool doMute = false;
7388
François Gaffiec005e562018-11-06 15:04:49 +01007389 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007390 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007391 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7392 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007393 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007394 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007395 }
Eric Laurent99401132014-05-07 19:48:15 -07007396 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007397 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007398 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007399 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007400 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007401 continue;
7402 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307403 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007404 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7405 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7406 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007407 if (mute) {
7408 // FIXME: should not need to double latency if volume could be applied
7409 // immediately by the audioflinger mixer. We must account for the delay
7410 // between now and the next time the audioflinger thread for this output
7411 // will process a buffer (which corresponds to one buffer size,
7412 // usually 1/2 or 1/4 of the latency).
7413 if (muteWaitMs < desc->latency() * 2) {
7414 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007415 }
7416 }
7417 }
7418 }
7419 }
7420 }
7421
Eric Laurent99401132014-05-07 19:48:15 -07007422 // temporary mute output if device selection changes to avoid volume bursts due to
7423 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007424 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007425 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007426
Eric Laurentdc462862016-07-19 12:29:53 -07007427 if (muteWaitMs < tempMuteWaitMs) {
7428 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007429 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007430
7431 // If recommended duration is defined, replace temporary mute duration to avoid
7432 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7433 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7434 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7435 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7436 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7437
François Gaffieaaac0fd2018-11-22 17:56:39 +01007438 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7439 // make sure that we do not start the temporary mute period too early in case of
7440 // delayed device change
7441 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7442 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007443 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007444 }
7445 }
7446
Eric Laurente552edb2014-03-10 17:42:56 -07007447 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7448 if (muteWaitMs > delayMs) {
7449 muteWaitMs -= delayMs;
7450 usleep(muteWaitMs * 1000);
7451 return muteWaitMs;
7452 }
7453 return 0;
7454}
7455
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307456uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7457 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007458 const DeviceVector &devices,
7459 bool force,
7460 int delayMs,
7461 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007462 bool requiresMuteCheck, bool requiresVolumeCheck,
7463 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007464{
jiabin3ff8d7d2022-12-13 06:27:44 +00007465 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307466 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7467 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7468 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007469 uint32_t muteWaitMs;
7470
7471 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307472 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007473 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307474 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007475 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007476 return muteWaitMs;
7477 }
Eric Laurente552edb2014-03-10 17:42:56 -07007478
7479 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007480 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007481 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007482 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007483
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307484 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7485 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007486
7487 if (!filteredDevices.isEmpty()) {
7488 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007489 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007490
7491 // if the outputs are not materially active, there is no need to mute.
7492 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007493 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007494 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307495 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7496 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007497 muteWaitMs = 0;
7498 }
Eric Laurente552edb2014-03-10 17:42:56 -07007499
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007500 bool outputRouted = outputDesc->isRouted();
7501
Eric Laurent79ea9582020-06-11 18:49:24 -07007502 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7503 // output profile or if new device is not supported AND previous device(s) is(are) still
7504 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007505 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307506 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7507 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007508 // restore previous device after evaluating strategy mute state
7509 outputDesc->setDevices(prevDevices);
7510 return muteWaitMs;
7511 }
7512
Eric Laurente552edb2014-03-10 17:42:56 -07007513 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007514 // the requested device is AUDIO_DEVICE_NONE
7515 // OR the requested device is the same as current device
7516 // AND force is not specified
7517 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007518 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007519 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307520 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7521 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7522 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007523 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307524 ALOGV("%s %s setting same device on routed output, force apply volumes",
7525 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007526 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7527 }
Eric Laurente552edb2014-03-10 17:42:56 -07007528 return muteWaitMs;
7529 }
7530
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307531 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7532 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007533
Eric Laurente552edb2014-03-10 17:42:56 -07007534 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007535 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007536 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007537 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007538 PatchBuilder patchBuilder;
7539 patchBuilder.addSource(outputDesc);
7540 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7541 for (const auto &filteredDevice : filteredDevices) {
7542 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007543 }
7544
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007545 // Add half reported latency to delayMs when muteWaitMs is null in order
7546 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007547 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7548 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7549 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007550 }
Eric Laurente552edb2014-03-10 17:42:56 -07007551
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007552 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7553 if (!skipMuteDelay) {
7554 // update stream volumes according to new device
7555 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7556 }
Eric Laurente552edb2014-03-10 17:42:56 -07007557
7558 return muteWaitMs;
7559}
7560
Eric Laurentc75307b2015-03-17 15:29:32 -07007561status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007562 int delayMs,
7563 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007564{
Eric Laurent6a94d692014-05-20 11:18:06 -07007565 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007566 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7567 return INVALID_OPERATION;
7568 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007569 if (patchHandle) {
7570 index = mAudioPatches.indexOfKey(*patchHandle);
7571 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007572 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007573 }
7574 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007575 return INVALID_OPERATION;
7576 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007577 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007578 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007579 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007580 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007581 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007582 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007583 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007584 return status;
7585}
7586
7587status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007588 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007589 bool force,
7590 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007591{
7592 status_t status = NO_ERROR;
7593
Eric Laurent1f2f2232014-06-02 12:01:23 -07007594 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007595 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7596 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007597
François Gaffie11d30102018-11-02 16:09:09 +01007598 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007599 PatchBuilder patchBuilder;
7600 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007601 // AUDIO_SOURCE_HOTWORD is for internal use only:
7602 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007603 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7604 auto result = usecase;
7605 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7606 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7607 }
7608 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007609 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007610 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007611 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007612 }
7613 }
7614 return status;
7615}
7616
Eric Laurent6a94d692014-05-20 11:18:06 -07007617status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7618 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007619{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007620 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007621 ssize_t index;
7622 if (patchHandle) {
7623 index = mAudioPatches.indexOfKey(*patchHandle);
7624 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007625 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007626 }
7627 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007628 return INVALID_OPERATION;
7629 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007630 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007631 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007632 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007633 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007634 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007635 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007636 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007637 return status;
7638}
7639
François Gaffie11d30102018-11-02 16:09:09 +01007640sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007641 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007642 audio_format_t& format,
7643 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007644 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007645{
7646 // Choose an input profile based on the requested capture parameters: select the first available
7647 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007648 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007649 //
7650 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7651 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007652
Atneya Nair0f0a8032022-12-12 16:20:12 -08007653 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7654 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7655 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7656
7657 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007658
jiabin2fd710d2022-05-02 23:20:22 +00007659 for (;;) {
7660 sp<IOProfile> firstInexact = nullptr;
7661 uint32_t updatedSamplingRate = 0;
7662 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7663 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7664 for (const auto& hwModule : mHwModules) {
7665 for (const auto& profile : hwModule->getInputProfiles()) {
7666 // profile->log();
7667 //updatedFormat = format;
7668 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7669 &samplingRate /*updatedSamplingRate*/,
7670 format,
7671 &format, /*updatedFormat*/
7672 channelMask,
7673 &channelMask /*updatedChannelMask*/,
7674 // FIXME ugly cast
7675 (audio_output_flags_t) flags,
7676 true /*exactMatchRequiredForInputFlags*/)) {
7677 return profile;
7678 }
7679 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7680 samplingRate,
7681 &updatedSamplingRate,
7682 format,
7683 &updatedFormat,
7684 channelMask,
7685 &updatedChannelMask,
7686 // FIXME ugly cast
7687 (audio_output_flags_t) flags,
7688 false /*exactMatchRequiredForInputFlags*/)) {
7689 firstInexact = profile;
7690 }
7691 }
7692 }
7693
7694 if (firstInexact != nullptr) {
7695 samplingRate = updatedSamplingRate;
7696 format = updatedFormat;
7697 channelMask = updatedChannelMask;
7698 return firstInexact;
7699 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7700 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7701 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7702 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7703 flags = AUDIO_INPUT_FLAG_NONE;
7704 } else { // fail
7705 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7706 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7707 samplingRate, format, channelMask, oriFlags);
7708 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007709 }
7710 }
jiabin2fd710d2022-05-02 23:20:22 +00007711
7712 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007713}
7714
François Gaffieaaac0fd2018-11-22 17:56:39 +01007715float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7716 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007717 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007718 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007719{
jiabin9a3361e2019-10-01 09:38:30 -07007720 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007721
7722 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7723 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7724 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7725 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007726 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7727 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7728 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7729 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7730 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena437ded52023-08-30 18:45:18 -07007731 // Verify that the current volume source is not the ringer volume to prevent recursively
7732 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7733 // to the same volume group.
7734 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007735 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7736 mOutputs.isActive(ringVolumeSrc, 0)) {
7737 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007738 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007739 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007740 }
7741
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007742 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007743 if ((volumeSource != callVolumeSrc && (isInCall() ||
7744 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007745 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007746 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7747 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007748 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7749 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7750 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007751 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007752 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007753 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007754 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007755 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007756 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007757 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7758 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7759 // programmatically muted.
7760 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7761 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7762 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007763 bool exemptFromCapping =
7764 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7765 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007766 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7767 volumeSource, volumeDb);
7768 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007769 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7770 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7771 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007772 }
7773 }
Eric Laurente552edb2014-03-10 17:42:56 -07007774 // if a headset is connected, apply the following rules to ring tones and notifications
7775 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007776 // - always attenuate notifications volume by 6dB
7777 // - attenuate ring tones volume by 6dB unless music is not playing and
7778 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007779 // - if music is playing, always limit the volume to current music volume,
7780 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007781 if (!Intersection(deviceTypes,
7782 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7783 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007784 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7785 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007786 ((volumeSource == alarmVolumeSrc ||
7787 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007788 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7789 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7790 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007791 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7792 curves.canBeMuted()) {
7793
Eric Laurente552edb2014-03-10 17:42:56 -07007794 // when the phone is ringing we must consider that music could have been paused just before
7795 // by the music application and behave as if music was active if the last music track was
7796 // just stopped
Oscar Azucena437ded52023-08-30 18:45:18 -07007797 // Verify that the current volume source is not the music volume to prevent recursively
7798 // calling to compute volume. This could happen in cases where music and
7799 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7800 if (volumeSource != musicVolumeSrc &&
7801 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7802 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007803 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007804 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007805 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7806 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007807 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007808 float musicVolDb = computeVolume(musicCurves,
7809 musicVolumeSrc,
7810 musicCurves.getVolumeIndex(musicDevice),
7811 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007812 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7813 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7814 if (volumeDb > minVolDb) {
7815 volumeDb = minVolDb;
7816 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007817 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007818 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7819 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7820 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007821 // on A2DP, also ensure notification volume is not too low compared to media when
7822 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007823 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007824 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007825 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7826 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007827 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7828 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007829 }
7830 }
jiabin9a3361e2019-10-01 09:38:30 -07007831 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007832 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007833 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007834 }
7835 }
7836
François Gaffie43c73442018-11-08 08:21:55 +01007837 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007838}
7839
Eric Laurent3839bc02018-07-10 18:33:34 -07007840int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007841 VolumeSource fromVolumeSource,
7842 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007843{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007844 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007845 return srcIndex;
7846 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007847 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7848 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007849 float minSrc = (float)srcCurves.getVolumeIndexMin();
7850 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7851 float minDst = (float)dstCurves.getVolumeIndexMin();
7852 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007853
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007854 // preserve mute request or correct range
7855 if (srcIndex < minSrc) {
7856 if (srcIndex == 0) {
7857 return 0;
7858 }
7859 srcIndex = minSrc;
7860 } else if (srcIndex > maxSrc) {
7861 srcIndex = maxSrc;
7862 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007863 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7864}
7865
François Gaffieaaac0fd2018-11-22 17:56:39 +01007866status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7867 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007868 int index,
7869 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007870 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007871 int delayMs,
7872 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007873{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007874 // do not change actual attributes volume if the attributes is muted
7875 if (outputDesc->isMuted(volumeSource)) {
7876 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7877 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007878 return NO_ERROR;
7879 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007880 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7881 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7882 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7883 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007884
Eric Laurent2517af32020-11-25 15:31:27 +01007885 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007886 bool isHAUsed = isHearingAidUsedForComm();
7887
Eric Laurente552edb2014-03-10 17:42:56 -07007888 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007889 // if sco and call follow same curves, bypass forceUseForComm
7890 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007891 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007892 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7893 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007894 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007895 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007896 // Do not return an error here as AudioService will always set both voice call
7897 // and bluetooth SCO volumes due to stream aliasing.
7898 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007899 }
jiabin9a3361e2019-10-01 09:38:30 -07007900 if (deviceTypes.empty()) {
7901 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007902 index = curves.getVolumeIndex(deviceTypes);
7903 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7904 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007905 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007906
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007907 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7908 ALOGE("invalid volume index range");
7909 return BAD_VALUE;
7910 }
7911
jiabin9a3361e2019-10-01 09:38:30 -07007912 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7913 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007914 // Force VoIP volume to max for bluetooth SCO device except if muted
7915 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007916 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007917 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007918 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007919 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007920 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7921 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007922
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007923 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007924 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007925 // 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 +01007926 if (isVoiceVolSrc) {
7927 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007928 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007929 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007930 }
Eric Laurent18fba842016-03-31 14:41:26 -07007931 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007932 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7933 mLastVoiceVolume = voiceVolume;
7934 }
7935 }
Eric Laurente552edb2014-03-10 17:42:56 -07007936 return NO_ERROR;
7937}
7938
Eric Laurentc75307b2015-03-17 15:29:32 -07007939void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007940 const DeviceTypeSet& deviceTypes,
7941 int delayMs,
7942 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007943{
jiabincd510522020-01-22 09:40:55 -08007944 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007945 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7946 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7947 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007948 curves.getVolumeIndex(deviceTypes),
7949 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007950 }
7951}
7952
François Gaffiec005e562018-11-06 15:04:49 +01007953void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
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{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007959 std::vector<VolumeSource> sourcesToMute;
7960 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7961 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7962 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007963 VolumeSource source = toVolumeSource(attributes, false);
7964 if ((source != VOLUME_SOURCE_NONE) &&
7965 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7966 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007967 sourcesToMute.push_back(source);
7968 }
Eric Laurente552edb2014-03-10 17:42:56 -07007969 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007970 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007971 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007972 }
7973
Eric Laurente552edb2014-03-10 17:42:56 -07007974}
7975
François Gaffieaaac0fd2018-11-22 17:56:39 +01007976void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7977 bool on,
7978 const sp<AudioOutputDescriptor>& outputDesc,
7979 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007980 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007981{
jiabin9a3361e2019-10-01 09:38:30 -07007982 if (deviceTypes.empty()) {
7983 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007984 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007985 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007986 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007987 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007988 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007989 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007990 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7991 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007992 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007993 }
7994 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007995 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7996 // ignored
7997 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007998 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007999 if (!outputDesc->isMuted(volumeSource)) {
8000 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008001 return;
8002 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008003 if (outputDesc->decMuteCount(volumeSource) == 0) {
8004 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008005 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008006 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008007 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008008 delayMs);
8009 }
8010 }
8011}
8012
François Gaffie53615e22015-03-19 09:24:12 +01008013bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8014{
François Gaffiec005e562018-11-06 15:04:49 +01008015 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008016 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8017 return true;
8018 }
8019
8020 // has known usage?
8021 switch (paa->usage) {
8022 case AUDIO_USAGE_UNKNOWN:
8023 case AUDIO_USAGE_MEDIA:
8024 case AUDIO_USAGE_VOICE_COMMUNICATION:
8025 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8026 case AUDIO_USAGE_ALARM:
8027 case AUDIO_USAGE_NOTIFICATION:
8028 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8029 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8030 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8031 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8032 case AUDIO_USAGE_NOTIFICATION_EVENT:
8033 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8034 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8035 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8036 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008037 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008038 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008039 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008040 case AUDIO_USAGE_EMERGENCY:
8041 case AUDIO_USAGE_SAFETY:
8042 case AUDIO_USAGE_VEHICLE_STATUS:
8043 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008044 break;
8045 default:
8046 return false;
8047 }
8048 return true;
8049}
8050
François Gaffie2110e042015-03-24 08:41:51 +01008051audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8052{
8053 return mEngine->getForceUse(usage);
8054}
8055
Eric Laurent96d1dda2022-03-14 17:14:19 +01008056bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008057 return isStateInCall(mEngine->getPhoneState());
8058}
8059
Eric Laurent96d1dda2022-03-14 17:14:19 +01008060bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008061 return is_state_in_call(state);
8062}
8063
Eric Laurentf9cccec2022-11-16 19:12:00 +01008064bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008065 audio_mode_t mode = mEngine->getPhoneState();
8066 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008067 || (mode == AUDIO_MODE_CALL_SCREEN)
8068 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008069}
8070
Eric Laurentf9cccec2022-11-16 19:12:00 +01008071bool AudioPolicyManager::isInCallOrScreening() const {
8072 audio_mode_t mode = mEngine->getPhoneState();
8073 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8074}
8075
Eric Laurentd60560a2015-04-10 11:31:20 -07008076void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8077{
8078 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008079 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008080 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008081 sourceDesc->sinkDevice()->equals(deviceDesc))
8082 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008083 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008084 }
8085 }
8086
8087 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8088 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8089 bool release = false;
8090 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8091 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8092 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8093 source->ext.device.type == deviceDesc->type()) {
8094 release = true;
8095 }
8096 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008097 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008098 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8099 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8100 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008101 sink->ext.device.type == deviceDesc->type() &&
8102 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8103 || strncmp(sink->ext.device.address, address,
8104 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008105 release = true;
8106 }
8107 }
8108 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008109 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8110 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008111 }
8112 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008113
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008114 mInputs.clearSessionRoutesForDevice(deviceDesc);
8115
Francois Gaffie716e1432019-01-14 16:58:59 +01008116 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008117}
8118
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008119void AudioPolicyManager::modifySurroundFormats(
8120 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008121 std::unordered_set<audio_format_t> enforcedSurround(
8122 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008123 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008124 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008125 allSurround.insert(pair.first);
8126 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8127 }
Phil Burk09bc4612016-02-24 15:58:15 -08008128
8129 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8130 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008131 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008132 // This is the resulting set of formats depending on the surround mode:
8133 // 'all surround' = allSurround
8134 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8135 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8136 // 'manual surround' = mManualSurroundFormats
8137 // AUTO: formats v 'enforced surround'
8138 // ALWAYS: formats v 'all surround' v 'enforced surround'
8139 // NEVER: formats ^ 'non-surround'
8140 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008141
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008142 std::unordered_set<audio_format_t> formatSet;
8143 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8144 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008145 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008146 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008147 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008148 formatSet.insert(*formatIter);
8149 }
8150 }
8151 } else {
8152 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8153 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008154 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008155
jiabin81772902018-04-02 17:52:27 -07008156 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008157 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008158 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8159 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8160 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008161 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008162 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8163 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8164 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008165 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008166 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008167 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008168 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008169 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008170 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008171}
8172
jiabin06e4bab2019-07-29 10:13:34 -07008173void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8174 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008175 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8176 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8177
8178 // If NEVER, then remove support for channelMasks > stereo.
8179 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008180 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8181 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008182 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008183 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008184 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008185 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008186 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008187 }
8188 }
jiabin81772902018-04-02 17:52:27 -07008189 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8190 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8191 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008192 bool supports5dot1 = false;
8193 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008194 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008195 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8196 supports5dot1 = true;
8197 break;
8198 }
8199 }
8200 // If not then add 5.1 support.
8201 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008202 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008203 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008204 }
Phil Burk09bc4612016-02-24 15:58:15 -08008205 }
8206}
8207
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008208void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008209 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008210 const sp<IOProfile>& profile) {
8211 if (!profile->hasDynamicAudioProfile()) {
8212 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008213 }
François Gaffie112b0af2015-11-19 16:13:25 +01008214
jiabin12537fc2023-10-12 17:56:08 +00008215 audio_port_v7 devicePort;
8216 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008217
jiabin12537fc2023-10-12 17:56:08 +00008218 audio_port_v7 mixPort;
8219 profile->toAudioPort(&mixPort);
8220 mixPort.ext.mix.handle = ioHandle;
8221
8222 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8223 if (status != NO_ERROR) {
8224 ALOGE("%s failed to query the attributes of the mix port", __func__);
8225 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008226 }
jiabin12537fc2023-10-12 17:56:08 +00008227
8228 std::set<audio_format_t> supportedFormats;
8229 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8230 supportedFormats.insert(mixPort.audio_profiles[i].format);
8231 }
8232 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8233 mReportedFormatsMap[devDesc] = formats;
8234
8235 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8236 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8237 modifySurroundFormats(devDesc, &formats);
8238 size_t modifiedNumProfiles = 0;
8239 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8240 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8241 formats.end()) {
8242 // Skip the format that is not present after modifying surround formats.
8243 continue;
8244 }
8245 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8246 sizeof(struct audio_profile));
8247 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8248 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8249 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8250 modifySurroundChannelMasks(&channels);
8251 std::copy(channels.begin(), channels.end(),
8252 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8253 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8254 }
8255 mixPort.num_audio_profiles = modifiedNumProfiles;
8256 }
8257 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008258}
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 }
jiabin14b50cc2023-12-13 19:01:52 +00008374 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8375 auto portConfig = desc->getConfig();
8376 for (const auto& device : devices) {
8377 device->setPreferredConfig(&portConfig);
8378 }
8379 }
jiabinbce0c1d2020-10-05 11:20:18 -07008380
8381 // Here is where the out_set_parameters() for card & device gets called
8382 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8383 const audio_devices_t deviceType = device->type();
8384 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008385 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008386 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8387 mpClientInterface->setParameters(output, String8(param));
8388 free(param);
8389 }
jiabin12537fc2023-10-12 17:56:08 +00008390 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008391 if (!profile->hasValidAudioProfile()) {
8392 ALOGW("%s() missing param", __func__);
8393 desc->close();
8394 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008395 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8396 // Reopen the output with the best audio profile picked by APM when the profile supports
8397 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008398 desc->close();
8399 output = AUDIO_IO_HANDLE_NONE;
8400 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8401 profile->pickAudioProfile(
8402 config.sample_rate, config.channel_mask, config.format);
8403 config.offload_info.sample_rate = config.sample_rate;
8404 config.offload_info.channel_mask = config.channel_mask;
8405 config.offload_info.format = config.format;
8406
jiabina84c3d32022-12-02 18:59:55 +00008407 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008408 if (status != NO_ERROR) {
8409 return nullptr;
8410 }
8411 }
8412
8413 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008414
baek.kim -61c20122022-07-27 10:05:32 +00008415 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8416 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8417
jiabinbce0c1d2020-10-05 11:20:18 -07008418 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8419 sp<AudioPolicyMix> policyMix;
8420 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8421 policyMix->setOutput(desc);
8422 desc->mPolicyMix = policyMix;
8423 } else {
8424 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008425 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008426 }
8427
baek.kim -61c20122022-07-27 10:05:32 +00008428 } else if (hasPrimaryOutput() && speaker != nullptr
8429 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008430 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8431 // no duplicated output for:
8432 // - direct outputs
8433 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008434 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008435 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8436
8437 //TODO: configure audio effect output stage here
8438
8439 // open a duplicating output thread for the new output and the primary output
8440 sp<SwAudioOutputDescriptor> dupOutputDesc =
8441 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8442 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8443 if (status == NO_ERROR) {
8444 // add duplicated output descriptor
8445 addOutput(duplicatedOutput, dupOutputDesc);
8446 } else {
8447 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8448 mPrimaryOutput->mIoHandle, output);
8449 desc->close();
8450 removeOutput(output);
8451 nextAudioPortGeneration();
8452 return nullptr;
8453 }
8454 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008455 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8456 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8457 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008458 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008459 }
jiabinbce0c1d2020-10-05 11:20:18 -07008460 return desc;
8461}
8462
jiabinf1c73972022-04-14 16:28:52 -07008463status_t AudioPolicyManager::getDevicesForAttributes(
8464 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8465 // Devices are determined in the following precedence:
8466 //
8467 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8468 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8469 //
8470 // If no such dynamic policy then
8471 // 2) Devices containing an active client using setPreferredDevice
8472 // with same strategy as the attributes.
8473 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8474 //
8475 // If no corresponding active client with setPreferredDevice then
8476 // 3) Devices associated with the strategy determined by the attributes
8477 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8478 //
8479 // See related getOutputForAttrInt().
8480
8481 // check dynamic policies but only for primary descriptors (secondary not used for audible
8482 // audio routing, only used for duplication for playback capture)
8483 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008484 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008485 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008486 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8487 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8488 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008489 if (status != OK) {
8490 return status;
8491 }
8492
8493 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8494 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8495 // as they are unaffected by device/stream volume
8496 // (per SwAudioOutputDescriptor::isFixedVolume()).
8497 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8498 ) {
8499 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8500 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8501 devices.add(deviceDesc);
8502 } else {
8503 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8504 // which selects setPreferredDevice if active. This means forVolume call
8505 // will take an active setPreferredDevice, if such exists.
8506
8507 devices = mEngine->getOutputDevicesForAttributes(
8508 attr, nullptr /* preferredDevice */, false /* fromCache */);
8509 }
8510
8511 if (forVolume) {
8512 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8513 // for single volume control in AudioService (such relationship should exist if
8514 // SPEAKER_SAFE is present).
8515 //
8516 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8517 DeviceVector speakerSafeDevices =
8518 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8519 if (!speakerSafeDevices.isEmpty()) {
8520 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8521 devices.remove(speakerSafeDevices);
8522 }
8523 }
8524
8525 return NO_ERROR;
8526}
8527
8528status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8529 AudioProfileVector& audioProfiles,
8530 uint32_t flags,
8531 bool isInput) {
8532 for (const auto& hwModule : mHwModules) {
8533 // the MSD module checks for different conditions
8534 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8535 continue;
8536 }
8537 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8538 : hwModule->getOutputProfiles();
8539 for (const auto& profile : ioProfiles) {
8540 if (!profile->areAllDevicesSupported(devices) ||
8541 !profile->isCompatibleProfileForFlags(
8542 flags, false /*exactMatchRequiredForInputFlags*/)) {
8543 continue;
8544 }
8545 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8546 }
8547 }
8548
8549 if (!isInput) {
8550 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8551 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8552 if (msdModule != nullptr) {
8553 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8554 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8555 for (const auto &profile: msdModule->getOutputProfiles()) {
8556 if (!profile->asAudioPort()->isDirectOutput()) {
8557 continue;
8558 }
8559 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8560 }
8561 } else {
8562 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8563 }
8564 }
8565 }
8566
8567 return NO_ERROR;
8568}
8569
jiabin3ff8d7d2022-12-13 06:27:44 +00008570sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8571 const audio_config_t *config,
8572 audio_output_flags_t flags,
8573 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008574 closeOutput(outputDesc->mIoHandle);
8575 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8576 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8577 if (preferredOutput == nullptr) {
8578 ALOGE("%s failed to reopen output device=%d, caller=%s",
8579 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008580 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008581 return preferredOutput;
8582}
8583
8584void AudioPolicyManager::reopenOutputsWithDevices(
8585 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8586 for (const auto& [output, devices] : outputsToReopen) {
8587 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8588 closeOutput(output);
8589 openOutputWithProfileAndDevice(desc->mProfile, devices);
8590 }
jiabina84c3d32022-12-02 18:59:55 +00008591}
8592
jiabinc44b3462022-12-08 12:52:31 -08008593PortHandleVector AudioPolicyManager::getClientsForStream(
8594 audio_stream_type_t streamType) const {
8595 PortHandleVector clients;
8596 for (size_t i = 0; i < mOutputs.size(); ++i) {
8597 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8598 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8599 }
8600 return clients;
8601}
8602
8603void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8604 PortHandleVector clients;
8605 for (auto stream : streams) {
8606 PortHandleVector clientsForStream = getClientsForStream(stream);
8607 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8608 }
8609 mpClientInterface->invalidateTracks(clients);
8610}
8611
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008612} // namespace android