blob: 22e4686135524113dc807f4472dddc24ef199561 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Eric Laurent16c66dd2019-05-01 17:54:10 -070032#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070033#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000034#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080036#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080037#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080038#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110039#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070040
41#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010042#include <android/media/audio/common/AudioPort.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070043#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070044#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070046#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070047#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070048#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070049#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070050#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070051#include <utils/Log.h>
52
Eric Laurentd4692962014-05-05 18:13:44 -070053#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010054#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070055
Eric Laurent3b73df72014-03-11 09:06:29 -070056namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070057
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010058using android::media::audio::common::AudioDevice;
59using android::media::audio::common::AudioDeviceAddress;
60using android::media::audio::common::AudioPortDeviceExt;
61using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000062using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070063
Eric Laurentdc462862016-07-19 12:29:53 -070064//FIXME: workaround for truncated touch sounds
65// to be removed when the problem is handled by system UI
66#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070067
68// Largest difference in dB on earpiece in call between the voice volume and another
69// media / notification / system volume.
70constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
71
jiabin06e4bab2019-07-29 10:13:34 -070072template <typename T>
73bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
74{
75 if (left.size() != right.size()) {
76 return false;
77 }
78 for (size_t index = 0; index < right.size(); index++) {
79 if (left[index] != right[index]) {
80 return false;
81 }
82 }
83 return true;
84}
85
86template <typename T>
87bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
88{
89 return !(left == right);
90}
91
Eric Laurente552edb2014-03-10 17:42:56 -070092// ----------------------------------------------------------------------------
93// AudioPolicyInterface implementation
94// ----------------------------------------------------------------------------
95
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010096status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
97 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
98 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -080099 nextAudioPortGeneration();
100 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800101}
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
104 audio_policy_dev_state_t state,
105 const char* device_address,
106 const char* device_name,
107 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800108 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100109 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
110 status == OK) {
111 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
112 } else {
113 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
114 return status;
115 }
116}
117
François Gaffie11d30102018-11-02 16:09:09 +0100118void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
119 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200120{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000121 audio_port_v7 devicePort;
122 device->toAudioPort(&devicePort);
123 if (status_t status = mpClientInterface->setDeviceConnectedState(
124 &devicePort, state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
125 status != OK) {
126 ALOGE("Error %d while setting connected state for device %s", status,
127 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...)
François Gaffie11d30102018-11-02 16:09:09 +0100209 broadcastDeviceConnectionState(device, state);
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
François Gaffie11d30102018-11-02 16:09:09 +0100216 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
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
Paul McLeane743a472015-01-28 11:07:31 -0800238 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100239 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700240
Eric Laurente552edb2014-03-10 17:42:56 -0700241 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100242 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700243
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100244 mOutputs.clearSessionRoutesForDevice(device);
245
François Gaffie11d30102018-11-02 16:09:09 +0100246 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100247
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800248 // Reset active device codec
249 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
250
Kriti Dangef6be8f2020-11-05 11:58:19 +0100251 // remove device from mReportedFormatsMap cache
252 mReportedFormatsMap.erase(device);
253
jiabina84c3d32022-12-02 18:59:55 +0000254 // remove preferred mixer configurations
255 mPreferredMixerAttrInfos.erase(device->getId());
256
Eric Laurente552edb2014-03-10 17:42:56 -0700257 } break;
258
259 default:
François Gaffie11d30102018-11-02 16:09:09 +0100260 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700261 return BAD_VALUE;
262 }
263
Eric Laurent736a1022019-03-27 18:28:46 -0700264 // Propagate device availability to Engine
265 setEngineDeviceConnectionState(device, state);
266
Eric Laurentae970022019-01-29 14:25:04 -0800267 // No need to evaluate playback routing when connecting a remote submix
268 // output device used by a dynamic policy of type recorder as no
269 // playback use case is affected.
270 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700271 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800272 for (audio_io_handle_t output : outputs) {
273 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800274 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
275 if (policyMix != nullptr
276 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700277 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800278 doCheckForDeviceAndOutputChanges = false;
279 break;
280 }
281 }
282 }
283
284 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700285 // outputs must be closed after checkOutputForAllStrategies() is executed
286 if (!outputs.isEmpty()) {
287 for (audio_io_handle_t output : outputs) {
288 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100289 // close unused outputs after device disconnection or direct outputs that have
290 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200291 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200292 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
293 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200294 (desc->mDirectOpenCount == 0))
295 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
296 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200297 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700298 closeOutput(output);
299 }
Eric Laurente552edb2014-03-10 17:42:56 -0700300 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700301 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
302 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700303 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700304 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800305 };
306
307 if (doCheckForDeviceAndOutputChanges) {
308 checkForDeviceAndOutputChanges(checkCloseOutputs);
309 } else {
310 checkCloseOutputs();
311 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100312 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100313 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700314 const DeviceVector activeMediaDevices =
315 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000316 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700317 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700318 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530319 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
320 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100321 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700322 // do not force device change on duplicated output because if device is 0, it will
323 // also force a device 0 for the two outputs it is duplicated to which may override
324 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100325 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100326 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700327 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700328 // always force when disconnecting (a non-duplicated device)
329 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin3ff8d7d2022-12-13 06:27:44 +0000330 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
331 // If the device is using preferred mixer attributes, the output need to reopen
332 // with default configuration when the new selected devices are different from
333 // current routing devices
334 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
335 continue;
336 }
François Gaffie11d30102018-11-02 16:09:09 +0100337 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700338 }
jiabinbce0c1d2020-10-05 11:20:18 -0700339 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000340 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700341 desc->supportsDevicesForPlayback(activeMediaDevices)) {
342 // Reopen the output to query the dynamic profiles when there is not active
343 // clients or all active clients will be rerouted. Otherwise, set the flag
344 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
345 // can be reopened to query dynamic profiles when all clients are inactive.
346 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000347 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700348 } else {
349 desc->mPendingReopenToQueryProfiles = true;
350 }
351 }
352 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
353 // Clear the flag that previously set for re-querying profiles.
354 desc->mPendingReopenToQueryProfiles = false;
355 }
356 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000357 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700358
Eric Laurentd60560a2015-04-10 11:31:20 -0700359 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100360 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700361 }
362
Eric Laurent96d1dda2022-03-14 17:14:19 +0100363 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
364
Eric Laurent72aa32f2014-05-30 18:51:48 -0700365 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700366 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700367 } // end if is output device
368
Eric Laurente552edb2014-03-10 17:42:56 -0700369 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700370 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100371 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700372 switch (state)
373 {
374 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700375 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700376 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100377 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700378 return INVALID_OPERATION;
379 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700380
381 if (mAvailableInputDevices.add(device) < 0) {
382 return NO_MEMORY;
383 }
384
François Gaffie44481e72016-04-20 07:49:57 +0200385 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
386 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100387 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200388
Eric Laurent0dd51852019-04-19 18:18:58 -0700389 if (checkInputsForDevice(device, state) != NO_ERROR) {
390 mAvailableInputDevices.remove(device);
391
François Gaffie11d30102018-11-02 16:09:09 +0100392 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100393
394 mHwModules.cleanUpForDevice(device);
395
Eric Laurentd4692962014-05-05 18:13:44 -0700396 return INVALID_OPERATION;
397 }
398
Eric Laurentd4692962014-05-05 18:13:44 -0700399 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700400
401 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700402 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700403 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100404 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700405 return INVALID_OPERATION;
406 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700407
François Gaffie11d30102018-11-02 16:09:09 +0100408 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700409
410 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100411 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700412
François Gaffie11d30102018-11-02 16:09:09 +0100413 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700414
415 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100416
417 // remove device from mReportedFormatsMap cache
418 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700419 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700420
421 default:
François Gaffie11d30102018-11-02 16:09:09 +0100422 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700423 return BAD_VALUE;
424 }
425
Eric Laurent736a1022019-03-27 18:28:46 -0700426 // Propagate device availability to Engine
427 setEngineDeviceConnectionState(device, state);
428
Eric Laurent0dd51852019-04-19 18:18:58 -0700429 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700430 // As the input device list can impact the output device selection, update
431 // getDeviceForStrategy() cache
432 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700433
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100434 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200435 // Reconnect Audio Source
436 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
437 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
438 checkAudioSourceForAttributes(attributes);
439 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700440 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100441 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700442 }
443
Eric Laurentb52c1522014-05-20 11:27:36 -0700444 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700445 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700446 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700447
François Gaffie11d30102018-11-02 16:09:09 +0100448 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700449 return BAD_VALUE;
450}
451
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100452status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
453 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800454 media::AudioPortFw* aidlPort) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100455 DeviceDescriptorBase devDescr(device, device_address);
456 devDescr.setName(device_name);
457 return devDescr.writeToParcelable(aidlPort);
458}
459
Eric Laurent736a1022019-03-27 18:28:46 -0700460void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
461 audio_policy_dev_state_t state) {
462
463 // the Engine does not have to know about remote submix devices used by dynamic audio policies
464 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
465 return;
466 }
467 mEngine->setDeviceConnectionState(device, state);
468}
469
470
Eric Laurente0720872014-03-11 09:30:41 -0700471audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100472 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700473{
Eric Laurent634b7142016-04-20 13:48:02 -0700474 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800475 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
476 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700477 (strlen(device_address) != 0)/*matchAddress*/);
478
479 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100480 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700481 device, device_address);
482 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
483 }
François Gaffie53615e22015-03-19 09:24:12 +0100484
Eric Laurent3a4311c2014-03-17 12:00:47 -0700485 DeviceVector *deviceVector;
486
Eric Laurente552edb2014-03-10 17:42:56 -0700487 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700488 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700489 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700490 deviceVector = &mAvailableInputDevices;
491 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100492 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700493 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700494 }
Eric Laurent634b7142016-04-20 13:48:02 -0700495
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800496 return (deviceVector->getDevice(
497 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700498 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800499}
500
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800501status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
502 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800503 const char *device_name,
504 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800505{
506 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700507 String8 reply;
508 AudioParameter param;
509 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800510
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800511 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
512 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800513
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800514 // connect/disconnect only 1 device at a time
515 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
516
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800517 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700518 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800519 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520 // Nothing to do: device is not connected
521 return NO_ERROR;
522 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800523 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800524
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700525 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800526 // configure codecs.
527 // Handle two specific cases by sending a set parameter to
528 // configure A2DP codecs. No need to toggle device state.
529 // Case 1: A2DP active device switches from primary to primary
530 // module
531 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200532 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700533 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800534 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
535 if (availablePrimaryOutputDevices().contains(devDesc) &&
536 (module != 0 && module->getHandle() == primaryHandle)) {
537 reply = mpClientInterface->getParameters(
538 AUDIO_IO_HANDLE_NONE,
539 String8(AudioParameter::keyReconfigA2dpSupported));
540 AudioParameter repliedParameters(reply);
541 repliedParameters.getInt(
542 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
543 if (isReconfigA2dpSupported) {
544 const String8 key(AudioParameter::keyReconfigA2dp);
545 param.add(key, String8("true"));
546 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
547 devDesc->setEncodedFormat(encodedFormat);
548 return NO_ERROR;
549 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700550 }
551 }
cnx421bd2dcc42020-07-11 14:58:44 +0800552 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
553 for (size_t i = 0; i < mOutputs.size(); i++) {
554 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
555 // mute media strategies and delay device switch by the largest
556 // This avoid sending the music tail into the earpiece or headset.
557 setStrategyMute(musicStrategy, true, desc);
558 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
559 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
560 nullptr, true /*fromCache*/).types());
561 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800562 // Toggle the device state: UNAVAILABLE -> AVAILABLE
563 // This will force reading again the device configuration
564 status = setDeviceConnectionState(device,
565 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800566 device_address, device_name,
567 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800568 if (status != NO_ERROR) {
569 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
570 status);
571 return status;
572 }
573
574 status = setDeviceConnectionState(device,
575 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800576 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800577 if (status != NO_ERROR) {
578 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
579 status);
580 return status;
581 }
582
583 return NO_ERROR;
584}
585
Pattydd807582021-11-04 21:01:03 +0800586status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
587 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800588{
Pattydd807582021-11-04 21:01:03 +0800589 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800590 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800591 std::unordered_set<audio_format_t> formatSet;
592 sp<HwModule> primaryModule =
593 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700594 if (primaryModule == nullptr) {
595 ALOGE("%s() unable to get primary module", __func__);
596 return NO_INIT;
597 }
Pattydd807582021-11-04 21:01:03 +0800598
599 DeviceTypeSet audioDeviceSet;
600
601 switch(device) {
602 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
603 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
604 break;
605 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800606 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
607 break;
608 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
609 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800610 break;
611 default:
612 ALOGE("%s() device type 0x%08x not supported", __func__, device);
613 return BAD_VALUE;
614 }
615
jiabin9a3361e2019-10-01 09:38:30 -0700616 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800617 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800618 for (const auto& device : declaredDevices) {
619 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800620 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800621 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800622 return status;
623}
624
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100625DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
626{
627 DeviceVector rxSinkdevices{};
628 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
629 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
630 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
631 auto rxSinkDevice = rxSinkdevices.itemAt(0);
632 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
633 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
634 // retrieve Rx Source device descriptor
635 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
636 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
637
638 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
639 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
640 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
641 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
642 return DeviceVector(rxSinkDevice);
643 }
644 }
645 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
646 // the device returned is not necessarily reachable via this output
647 // (filter later by setOutputDevices())
648 return getNewOutputDevices(mPrimaryOutput, fromCache);
649}
650
651status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
652{
653 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
654 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
655 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
656 }
657 return INVALID_OPERATION;
658}
659
660status_t AudioPolicyManager::updateCallRoutingInternal(
661 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700662{
663 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100664 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700665 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700666 if(!hasPrimaryOutput() ||
667 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100668 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700669 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100670 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100671
Francois Gaffie716e1432019-01-14 16:58:59 +0100672 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100673 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100674 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100675
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100676 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100677 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700678
Francois Gaffie601801d2021-06-22 13:27:39 +0200679 disconnectTelephonyAudioSource(mCallRxSourceClient);
680 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700681
François Gaffie9eb18552018-11-05 10:33:26 +0100682 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700683 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100684 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700685 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100686 // retrieve Rx Source and Tx Sink device descriptors
687 sp<DeviceDescriptor> rxSourceDevice =
688 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
689 String8(),
690 AUDIO_FORMAT_DEFAULT);
691 sp<DeviceDescriptor> txSinkDevice =
692 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
693 String8(),
694 AUDIO_FORMAT_DEFAULT);
695
696 // RX and TX Telephony device are declared by Primary Audio HAL
697 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
698 (telephonyRxModule->getHalVersionMajor() >= 3)) {
699 if (rxSourceDevice == 0 || txSinkDevice == 0) {
700 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100701 ALOGE("%s() no telephony Tx and/or RX device", __func__);
702 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100703 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100704 // createAudioPatchInternal now supports both HW / SW bridging
705 createRxPatch = true;
706 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100707 } else {
708 // If the RX device is on the primary HW module, then use legacy routing method for
709 // voice calls via setOutputDevice() on primary output.
710 // Otherwise, create two audio patches for TX and RX path.
711 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
712 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700713 // If the TX device is also on the primary HW module, setOutputDevice() will take care
714 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100715 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
716 (txSinkDevice != 0);
717 }
718 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
719 // Otherwise, create two audio patches for TX and RX path.
720 if (!createRxPatch) {
721 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700722 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200723 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800724 // If the TX device is on the primary HW module but RX device is
725 // on other HW module, SinkMetaData of telephony input should handle it
726 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700727 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700728 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100729 // terminate active capture if on the same HW module as the call TX source device
730 // FIXME: would be better to refine to only inputs whose profile connects to the
731 // call TX device but this information is not in the audio patch and logic here must be
732 // symmetric to the one in startInput()
733 for (const auto& activeDesc : mInputs.getActiveInputs()) {
734 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
735 closeActiveClients(activeDesc);
736 }
737 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200738 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800739 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100740 if (waitMs != nullptr) {
741 *waitMs = muteWaitMs;
742 }
743 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800744}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700745
Mikhail Naganov100f0122018-11-29 11:22:16 -0800746bool AudioPolicyManager::isDeviceOfModule(
747 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
748 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
749 if (module != 0) {
750 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
751 .indexOf(devDesc) != NAME_NOT_FOUND
752 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
753 .indexOf(devDesc) != NAME_NOT_FOUND;
754 }
755 return false;
756}
757
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200758void AudioPolicyManager::connectTelephonyRxAudioSource()
759{
Francois Gaffie601801d2021-06-22 13:27:39 +0200760 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200761 const struct audio_port_config source = {
762 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
763 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
764 };
765 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200766 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
767 ALOGE_IF(mCallRxSourceClient == nullptr,
768 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200769}
770
Francois Gaffie601801d2021-06-22 13:27:39 +0200771void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200772{
Francois Gaffie601801d2021-06-22 13:27:39 +0200773 if (clientDesc == nullptr) {
774 return;
775 }
776 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
777 "%s error stopping audio source", __func__);
778 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200779}
780
781void AudioPolicyManager::connectTelephonyTxAudioSource(
782 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
783 uint32_t delayMs)
784{
Francois Gaffie601801d2021-06-22 13:27:39 +0200785 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200786 if (srcDevice == nullptr || sinkDevice == nullptr) {
787 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
788 return;
789 }
790 PatchBuilder patchBuilder;
791 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
792 ALOGV("%s between source %s and sink %s", __func__,
793 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200794 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200795 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
796
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200797 struct audio_port_config source = {};
798 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200799 mCallTxSourceClient = new InternalSourceClientDescriptor(
800 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200801 mCommunnicationStrategy, toVolumeSource(aa));
802 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
803 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200804 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
805 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200806 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
807 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200808 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200809 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200810}
811
Eric Laurente0720872014-03-11 09:30:41 -0700812void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700813{
814 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100815 // store previous phone state for management of sonification strategy below
816 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100817 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100818
819 if (mEngine->setPhoneState(state) != NO_ERROR) {
820 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700821 return;
822 }
François Gaffie2110e042015-03-24 08:41:51 +0100823 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700824 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700825 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700826 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800827 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700828 }
829
François Gaffie2110e042015-03-24 08:41:51 +0100830 /**
831 * Switching to or from incall state or switching between telephony and VoIP lead to force
832 * routing command.
833 */
Eric Laurent74b71512019-11-06 17:21:57 -0800834 bool force = ((isStateInCall(oldState) != isStateInCall(state))
835 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700836
837 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700838 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700839
Eric Laurente552edb2014-03-10 17:42:56 -0700840 int delayMs = 0;
841 if (isStateInCall(state)) {
842 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100843 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
844 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700845 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700846 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700847 // mute media and sonification strategies and delay device switch by the largest
848 // latency of any output where either strategy is active.
849 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100850 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
851 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
852 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700853 (delayMs < (int)desc->latency()*2)) {
854 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700855 }
François Gaffiec005e562018-11-06 15:04:49 +0100856 setStrategyMute(musicStrategy, true, desc);
857 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
858 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
859 nullptr, true /*fromCache*/).types());
860 setStrategyMute(sonificationStrategy, true, desc);
861 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
862 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
863 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700864 }
865 }
866
Eric Laurent87ffa392015-05-22 10:32:38 -0700867 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700868 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100869 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700870 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100871 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
872 // force routing command to audio hardware when ending call
873 // even if no device change is needed
874 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
875 rxDevices = mPrimaryOutput->devices();
876 }
877 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200878 disconnectTelephonyAudioSource(mCallRxSourceClient);
879 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100880 }
François Gaffie11d30102018-11-02 16:09:09 +0100881 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700882 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700883 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700884
jiabin3ff8d7d2022-12-13 06:27:44 +0000885 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700886 // reevaluate routing on all outputs in case tracks have been started during the call
887 for (size_t i = 0; i < mOutputs.size(); i++) {
888 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100889 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200890 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
891 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000892 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
893 // If the device is using preferred mixer attributes, the output need to reopen
894 // with default configuration when the new selected devices are different from
895 // current routing devices.
896 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
897 continue;
898 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200899 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
900 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700901 }
902 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000903 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700904
Eric Laurent96d1dda2022-03-14 17:14:19 +0100905 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
906
Eric Laurente552edb2014-03-10 17:42:56 -0700907 if (isStateInCall(state)) {
908 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700909 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800910 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700911 }
912
913 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100914 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
915 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700916}
917
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700918audio_mode_t AudioPolicyManager::getPhoneState() {
919 return mEngine->getPhoneState();
920}
921
Eric Laurente0720872014-03-11 09:30:41 -0700922void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100923 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700924{
François Gaffie2110e042015-03-24 08:41:51 +0100925 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700926 if (config == mEngine->getForceUse(usage)) {
927 return;
928 }
Eric Laurente552edb2014-03-10 17:42:56 -0700929
François Gaffie2110e042015-03-24 08:41:51 +0100930 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
931 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
932 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700933 }
François Gaffie2110e042015-03-24 08:41:51 +0100934 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
935 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
936 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700937
938 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700939 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800940
Eric Laurent22fcda22019-05-17 16:28:47 -0700941 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
942 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800943 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700944 }
945
Eric Laurentdc462862016-07-19 12:29:53 -0700946 //FIXME: workaround for truncated touch sounds
947 // to be removed when the problem is handled by system UI
948 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700949 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
950 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
951 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700952
953 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100954 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700955}
956
Eric Laurente0720872014-03-11 09:30:41 -0700957void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700958{
959 ALOGV("setSystemProperty() property %s, value %s", property, value);
960}
961
Dorin Drimusecc9f422022-03-09 17:57:40 +0100962// Find an MSD output profile compatible with the parameters passed.
963// When "directOnly" is set, restrict search to profiles for direct outputs.
964sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
965 const DeviceVector& devices,
966 uint32_t samplingRate,
967 audio_format_t format,
968 audio_channel_mask_t channelMask,
969 audio_output_flags_t flags,
970 bool directOnly)
971{
972 flags = getRelevantFlags(flags, directOnly);
973
974 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
975 if (msdModule != nullptr) {
976 // for the msd module check if there are patches to the output devices
977 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
978 HwModuleCollection modules;
979 modules.add(msdModule);
980 return searchCompatibleProfileHwModules(
981 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
982 flags, directOnly);
983 }
984 }
985 return nullptr;
986}
987
Michael Chana94fbb22018-04-24 14:31:19 +1000988// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
989// search to profiles for direct outputs.
990sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100991 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000992 uint32_t samplingRate,
993 audio_format_t format,
994 audio_channel_mask_t channelMask,
995 audio_output_flags_t flags,
996 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700997{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100998 flags = getRelevantFlags(flags, directOnly);
999
1000 return searchCompatibleProfileHwModules(
1001 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1002}
1003
1004audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1005 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001006 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001007 // only retain flags that will drive the direct output profile selection
1008 // if explicitly requested
1009 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001010 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001011 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1012 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001013 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001014 return flags;
1015}
Eric Laurent861a6282015-05-18 15:40:16 -07001016
Dorin Drimusecc9f422022-03-09 17:57:40 +01001017sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1018 const HwModuleCollection& hwModules,
1019 const DeviceVector& devices,
1020 uint32_t samplingRate,
1021 audio_format_t format,
1022 audio_channel_mask_t channelMask,
1023 audio_output_flags_t flags,
1024 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001025 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001026 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001027 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001028 if (!curProfile->isCompatibleProfile(devices,
1029 samplingRate, NULL /*updatedSamplingRate*/,
1030 format, NULL /*updatedFormat*/,
1031 channelMask, NULL /*updatedChannelMask*/,
1032 flags)) {
1033 continue;
1034 }
1035 // reject profiles not corresponding to a device currently available
1036 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1037 continue;
1038 }
1039 // reject profiles if connected device does not support codec
1040 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1041 continue;
1042 }
1043 if (!directOnly) {
1044 return curProfile;
1045 }
1046
1047 // when searching for direct outputs, if several profiles are compatible, give priority
1048 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001049 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001050 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001051 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001052 }
1053 profile = curProfile;
1054 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1055 break;
1056 }
Eric Laurente552edb2014-03-10 17:42:56 -07001057 }
1058 }
Eric Laurent861a6282015-05-18 15:40:16 -07001059 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001060}
1061
Eric Laurentfa0f6742021-08-17 18:39:44 +02001062sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001063 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001064{
1065 for (const auto& hwModule : mHwModules) {
1066 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001067 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001068 continue;
1069 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001070 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001071 // reject profiles not corresponding to a device currently available
1072 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1073 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1074 continue;
1075 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001076 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1077 != devices.size()) {
1078 continue;
1079 }
1080 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001081 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1082 return curProfile;
1083 }
1084 }
1085 return nullptr;
1086}
1087
Eric Laurentf4e63452017-11-06 19:31:46 +00001088audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001089{
François Gaffiec005e562018-11-06 15:04:49 +01001090 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001091
1092 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1093 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1094 // format, flags, etc. This may result in some discrepancy for functions that utilize
1095 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1096 // and AudioSystem::getOutputSamplingRate().
1097
François Gaffie11d30102018-11-02 16:09:09 +01001098 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001099 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001100
François Gaffie11d30102018-11-02 16:09:09 +01001101 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1102 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001103 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001104}
1105
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001106status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1107 const audio_attributes_t *srcAttr,
1108 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001109{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001110 if (srcAttr != NULL) {
1111 if (!isValidAttributes(srcAttr)) {
1112 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1113 __func__,
1114 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1115 srcAttr->tags);
1116 return BAD_VALUE;
1117 }
1118 *dstAttr = *srcAttr;
1119 } else {
1120 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1121 ALOGE("%s: invalid stream type", __func__);
1122 return BAD_VALUE;
1123 }
François Gaffiec005e562018-11-06 15:04:49 +01001124 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001125 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001126
1127 // Only honor audibility enforced when required. The client will be
1128 // forced to reconnect if the forced usage changes.
1129 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001130 dstAttr->flags = static_cast<audio_flags_mask_t>(
1131 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001132 }
1133
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001134 return NO_ERROR;
1135}
1136
Kevin Rocard153f92d2018-12-18 18:33:28 -08001137status_t AudioPolicyManager::getOutputForAttrInt(
1138 audio_attributes_t *resultAttr,
1139 audio_io_handle_t *output,
1140 audio_session_t session,
1141 const audio_attributes_t *attr,
1142 audio_stream_type_t *stream,
1143 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001144 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001145 audio_output_flags_t *flags,
1146 audio_port_handle_t *selectedDeviceId,
1147 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001148 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001149 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001150 bool *isSpatialized,
1151 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001152{
François Gaffiec005e562018-11-06 15:04:49 +01001153 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001154 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001155 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001156 const sp<DeviceDescriptor> requestedDevice =
1157 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1158
Eric Laurent8a1095a2019-11-08 14:44:16 -08001159 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001160 *isSpatialized = false;
1161
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001162 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1163 if (status != NO_ERROR) {
1164 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001165 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001166 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001167 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001168 }
François Gaffiec005e562018-11-06 15:04:49 +01001169 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001170
François Gaffiec005e562018-11-06 15:04:49 +01001171 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1172 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001173
Oscar Azucena873d10f2023-01-12 18:34:42 -08001174 bool usePrimaryOutputFromPolicyMixes = false;
1175
Kevin Rocard153f92d2018-12-18 18:33:28 -08001176 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1177 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1178 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001179 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001180 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1181 .channel_mask = config->channel_mask,
1182 .format = config->format,
1183 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001184 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001185 mAvailableOutputDevices, requestedDevice, primaryMix,
1186 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001187 if (status != OK) {
1188 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001189 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001190
Kevin Rocard153f92d2018-12-18 18:33:28 -08001191 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001192 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1193 && !audio_is_linear_pcm(config->format)) {
1194 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001195 return BAD_VALUE;
1196 }
1197 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001198 sp<DeviceDescriptor> deviceDesc =
1199 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1200 primaryMix->mDeviceAddress,
1201 AUDIO_FORMAT_DEFAULT);
1202 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001203 bool tryDirectForFlags = policyDesc == nullptr ||
1204 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1205 // if a direct output can be opened to deliver the track's multi-channel content to the
1206 // output rather than being downmixed by the primary output, then use this direct
1207 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1208 // mix.
1209 bool tryDirectForChannelMask = policyDesc != nullptr
1210 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1211 audio_channel_count_from_out_mask(config->channel_mask));
1212 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001213 audio_io_handle_t newOutput;
1214 status = openDirectOutput(
1215 *stream, session, config,
1216 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1217 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001218 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001219 policyDesc = mOutputs.valueFor(newOutput);
1220 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001221 } else if (tryDirectForFlags) {
1222 policyDesc = nullptr;
1223 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001224 }
1225 if (policyDesc != nullptr) {
1226 policyDesc->mPolicyMix = primaryMix;
1227 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001228 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001229
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001230 ALOGV("getOutputForAttr() returns output %d", *output);
1231 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1232 *outputType = API_OUT_MIX_PLAYBACK;
1233 } else {
1234 *outputType = API_OUTPUT_LEGACY;
1235 }
1236 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001237 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001238 }
François Gaffiec005e562018-11-06 15:04:49 +01001239 // Virtual sources must always be dynamicaly or explicitly routed
1240 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1241 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1242 return BAD_VALUE;
1243 }
1244 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1245 // in order to let the choice of the order to future vendor engine
1246 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001247
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001248 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001249 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001250 }
1251
Nadav Barb2f18162018-07-18 13:01:53 +03001252 // Set incall music only if device was explicitly set, and fallback to the device which is
1253 // chosen by the engine if not.
1254 // FIXME: provide a more generic approach which is not device specific and move this back
1255 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001256 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001257 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001258 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001259 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001260 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001261 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001262 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001263 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001264 }
1265 }
1266
François Gaffiec005e562018-11-06 15:04:49 +01001267 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1268 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1269 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001270
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001271 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001272 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001273 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001274 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001275 ALOGV("%s() Using MSD devices %s instead of devices %s",
1276 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001277 } else {
1278 *output = AUDIO_IO_HANDLE_NONE;
1279 }
1280 }
1281 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001282 sp<PreferredMixerAttributesInfo> info = nullptr;
1283 if (outputDevices.size() == 1) {
1284 info = getPreferredMixerAttributesInfo(
1285 outputDevices.itemAt(0)->getId(),
1286 mEngine->getProductStrategyForAttributes(*resultAttr));
jiabin5eaf0962022-12-20 20:11:38 +00001287 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1288 // and it is currently active.
1289 if (info != nullptr && info->getUid() != uid &&
1290 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1291 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001292 info = nullptr;
1293 }
1294 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001295 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001296 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001297 // The client will be active if the client is currently preferred mixer owner and the
1298 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001299 *isBitPerfect = (info != nullptr
1300 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001301 && info->getUid() == uid
1302 && *output != AUDIO_IO_HANDLE_NONE
1303 // When bit-perfect output is selected for the preferred mixer attributes owner,
1304 // only need to consider the config matches.
1305 && mOutputs.valueFor(*output)->isConfigurationMatched(
1306 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001307 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001308 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001309 AudioProfileVector profiles;
1310 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1311 if (ret == NO_ERROR && !profiles.empty()) {
1312 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
1313 : *profiles[0]->getChannels().begin();
1314 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
1315 : *profiles[0]->getSampleRates().begin();
1316 config->format = profiles[0]->getFormat();
1317 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001318 return INVALID_OPERATION;
1319 }
Paul McLeanaa981192015-03-21 09:55:15 -07001320
François Gaffiec005e562018-11-06 15:04:49 +01001321 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001322 for (auto &outputDevice : outputDevices) {
1323 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1324 *selectedDeviceId = outputDevice->getId();
1325 break;
1326 }
1327 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001328
Eric Laurent8a1095a2019-11-08 14:44:16 -08001329 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1330 *outputType = API_OUTPUT_TELEPHONY_TX;
1331 } else {
1332 *outputType = API_OUTPUT_LEGACY;
1333 }
1334
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001335 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1336
1337 return NO_ERROR;
1338}
1339
1340status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1341 audio_io_handle_t *output,
1342 audio_session_t session,
1343 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001344 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001345 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001346 audio_output_flags_t *flags,
1347 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001348 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001349 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001350 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001351 bool *isSpatialized,
1352 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001353{
1354 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1355 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1356 return INVALID_OPERATION;
1357 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001358 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001359 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001360 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001361 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001362 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001363 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001364 const sp<DeviceDescriptor> requestedDevice =
1365 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1366
1367 // Prevent from storing invalid requested device id in clients
1368 const audio_port_handle_t sanitizedRequestedPortId =
1369 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1370 *selectedDeviceId = sanitizedRequestedPortId;
1371
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001372 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001373 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001374 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1375 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001376 if (status != NO_ERROR) {
1377 return status;
1378 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001379 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001380 if (secondaryOutputs != nullptr) {
1381 for (auto &secondaryMix : secondaryMixes) {
1382 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1383 if (outputDesc != nullptr &&
1384 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1385 secondaryOutputs->push_back(outputDesc->mIoHandle);
1386 weakSecondaryOutputDescs.push_back(outputDesc);
1387 }
1388 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001389 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001390
Eric Laurent8fc147b2018-07-22 19:13:55 -07001391 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001392 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001393 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001394 };
jiabin4ef93452019-09-10 14:29:54 -07001395 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001396
Eric Laurentc209fe42020-06-05 18:11:23 -07001397 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001398 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001399 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001400 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001401 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001402 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001403 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001404 std::move(weakSecondaryOutputDescs),
1405 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001406 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001407
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001408 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1409 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001410
Eric Laurente83b55d2014-11-14 10:06:21 -08001411 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001412}
1413
Eric Laurentc529cf62020-04-17 18:19:10 -07001414status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1415 audio_session_t session,
1416 const audio_config_t *config,
1417 audio_output_flags_t flags,
1418 const DeviceVector &devices,
1419 audio_io_handle_t *output) {
1420
1421 *output = AUDIO_IO_HANDLE_NONE;
1422
1423 // skip direct output selection if the request can obviously be attached to a mixed output
1424 // and not explicitly requested
1425 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1426 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1427 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1428 return NAME_NOT_FOUND;
1429 }
1430
1431 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1432 // This prevents creating an offloaded track and tearing it down immediately after start
1433 // when audioflinger detects there is an active non offloadable effect.
1434 // FIXME: We should check the audio session here but we do not have it in this context.
1435 // This may prevent offloading in rare situations where effects are left active by apps
1436 // in the background.
1437 sp<IOProfile> profile;
1438 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1439 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1440 profile = getProfileForOutput(
1441 devices, config->sample_rate, config->format, config->channel_mask,
1442 flags, true /* directOnly */);
1443 }
1444
1445 if (profile == nullptr) {
1446 return NAME_NOT_FOUND;
1447 }
1448
1449 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1450 for (size_t i = 0; i < mOutputs.size(); i++) {
1451 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1452 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1453 // reuse direct output if currently open by the same client
1454 // and configured with same parameters
1455 if ((config->sample_rate == desc->getSamplingRate()) &&
1456 (config->format == desc->getFormat()) &&
1457 (config->channel_mask == desc->getChannelMask()) &&
1458 (session == desc->mDirectClientSession)) {
1459 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001460 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001461 mOutputs.keyAt(i), session);
1462 *output = mOutputs.keyAt(i);
1463 return NO_ERROR;
1464 }
1465 }
1466 }
1467
1468 if (!profile->canOpenNewIo()) {
1469 return NAME_NOT_FOUND;
1470 }
1471
1472 sp<SwAudioOutputDescriptor> outputDesc =
1473 new SwAudioOutputDescriptor(profile, mpClientInterface);
1474
Michael Chan6fb34492020-12-08 15:44:49 +11001475 // An MSD patch may be using the only output stream that can service this request. Release
1476 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001477 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001478
Eric Laurentf1f22e72021-07-13 14:04:14 +02001479 status_t status =
1480 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001481
1482 // only accept an output with the requested parameters
1483 if (status != NO_ERROR ||
1484 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1485 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1486 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1487 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1488 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1489 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1490 config->channel_mask, outputDesc->getChannelMask());
1491 if (*output != AUDIO_IO_HANDLE_NONE) {
1492 outputDesc->close();
1493 }
1494 // fall back to mixer output if possible when the direct output could not be open
1495 if (audio_is_linear_pcm(config->format) &&
1496 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1497 return NAME_NOT_FOUND;
1498 }
1499 *output = AUDIO_IO_HANDLE_NONE;
1500 return BAD_VALUE;
1501 }
1502 outputDesc->mDirectOpenCount = 1;
1503 outputDesc->mDirectClientSession = session;
1504
1505 addOutput(*output, outputDesc);
1506 mPreviousOutputs = mOutputs;
1507 ALOGV("%s returns new direct output %d", __func__, *output);
1508 mpClientInterface->onAudioPortListUpdate();
1509 return NO_ERROR;
1510}
1511
François Gaffie11d30102018-11-02 16:09:09 +01001512audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1513 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001514 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001515 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001516 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001517 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001518 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001519 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001520 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001521{
Andy Hungc88b0642018-04-27 15:42:35 -07001522 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001523
jiabine375d412019-02-26 12:54:53 -08001524 // Discard haptic channel mask when forcing muting haptic channels.
1525 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001526 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1527 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001528
Eric Laurente552edb2014-03-10 17:42:56 -07001529 // open a direct output if required by specified parameters
1530 //force direct flag if offload flag is set: offloading implies a direct output stream
1531 // and all common behaviors are driven by checking only the direct flag
1532 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001533 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1534 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001535 }
Nadav Bar766fb022018-01-07 12:18:03 +02001536 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1537 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001538 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001539
1540 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1541
Eric Laurente83b55d2014-11-14 10:06:21 -08001542 // only allow deep buffering for music stream type
1543 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001544 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001545 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001546 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001547 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1548 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001549 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001550 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001551 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001552 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001553 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001554 audio_is_linear_pcm(config->format) &&
1555 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001556 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001557 AUDIO_OUTPUT_FLAG_DIRECT);
1558 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001559 }
Eric Laurente552edb2014-03-10 17:42:56 -07001560
Carter Hsua3abb402021-10-26 11:11:20 +08001561 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1562 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1563 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1564 }
1565
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001566 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001567 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001568 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001569 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001570 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001571 }
1572
Eric Laurentc529cf62020-04-17 18:19:10 -07001573 audio_config_t directConfig = *config;
1574 directConfig.channel_mask = channelMask;
1575 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1576 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001577 return output;
1578 }
1579
Eric Laurent14cbfca2016-03-17 09:42:16 -07001580 // A request for HW A/V sync cannot fallback to a mixed output because time
1581 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001582 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001583 return AUDIO_IO_HANDLE_NONE;
1584 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001585 // A request for Tuner cannot fallback to a mixed output
1586 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1587 return AUDIO_IO_HANDLE_NONE;
1588 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001589
Eric Laurente552edb2014-03-10 17:42:56 -07001590 // ignoring channel mask due to downmix capability in mixer
1591
1592 // open a non direct output
1593
1594 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001595 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001596 // get which output is suitable for the specified stream. The actual
1597 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001598 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001599 if (prefMixerConfigInfo != nullptr) {
1600 for (audio_io_handle_t outputHandle : outputs) {
1601 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1602 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1603 output = outputHandle;
1604 break;
1605 }
1606 }
1607 if (output == AUDIO_IO_HANDLE_NONE) {
1608 // No output open with the preferred profile. Open a new one.
1609 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1610 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1611 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1612 config.format = prefMixerConfigInfo->getConfigBase().format;
1613 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1614 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1615 &config, prefMixerConfigInfo->getFlags());
1616 if (preferredOutput == nullptr) {
1617 ALOGE("%s failed to open output with preferred mixer config", __func__);
1618 } else {
1619 output = preferredOutput->mIoHandle;
1620 }
1621 }
1622 } else {
1623 // at this stage we should ignore the DIRECT flag as no direct output could be
1624 // found earlier
1625 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1626 output = selectOutput(
1627 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1628 }
Eric Laurente552edb2014-03-10 17:42:56 -07001629 }
François Gaffie11d30102018-11-02 16:09:09 +01001630 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001631 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001632 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001633
Eric Laurente552edb2014-03-10 17:42:56 -07001634 return output;
1635}
1636
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001637sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001638 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1639 mAvailableInputDevices);
1640 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1641}
1642
1643DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1644 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1645 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001646}
1647
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001648const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001649 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001650 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1651 if (msdModule != 0) {
1652 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1653 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1654 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1655 const struct audio_port_config *source = &patch->mPatch.sources[j];
1656 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1657 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001658 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001659 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001660 }
1661 }
1662 }
1663 return msdPatches;
1664}
1665
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001666bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1667 ssize_t index = mAudioPatches.indexOfKey(handle);
1668 if (index < 0) {
1669 return false;
1670 }
1671 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1672 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1673 if (msdModule == nullptr) {
1674 return false;
1675 }
1676 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1677 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1678 return true;
1679 }
1680 index = getMsdOutputPatches().indexOfKey(handle);
1681 if (index < 0) {
1682 return false;
1683 }
1684 return true;
1685}
1686
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001687status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1688 const InputProfileCollection &inputProfiles,
1689 const OutputProfileCollection &outputProfiles,
1690 const sp<DeviceDescriptor> &sourceDevice,
1691 const sp<DeviceDescriptor> &sinkDevice,
1692 AudioProfileVector& sourceProfiles,
1693 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001694 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001695 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001696 return NO_INIT;
1697 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001698 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001699 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001700 return NO_INIT;
1701 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001702 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001703 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1704 inProfile->supportsDevice(sourceDevice)) {
1705 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001706 }
1707 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001708 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001709 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001710 outProfile->supportsDevice(sinkDevice)) {
1711 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001712 }
1713 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001714 return NO_ERROR;
1715}
1716
1717status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1718 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1719 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1720{
Dean Wheatley16809da2022-12-09 14:55:46 +11001721 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1722 static const std::vector<audio_format_t> formatsOrder = {{
1723 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1724 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1725 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1726 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1727 // preferred).
1728 std::vector<audio_channel_mask_t> masks = {{
1729 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1730 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1731 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1732 // insert index masks (higher counts most preferred) as preferred over position masks
1733 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1734 masks.insert(
1735 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1736 }
1737 return masks;
1738 }();
1739
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001740 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001741 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1742 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001743 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001744 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1745 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001746 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001747 }
1748 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1749 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1750 sinkConfig->format = bestSinkConfig.format;
1751 // For encoded streams force direct flag to prevent downstream mixing.
1752 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1753 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001754 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1755 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001756 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001757 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1758 // raw and IEC61937 framed streams.
1759 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1760 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1761 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001762 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1763 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001764 sourceConfig->channel_mask =
1765 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1766 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1767 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001768 sourceConfig->format = bestSinkConfig.format;
1769 // Copy input stream directly without any processing (e.g. resampling).
1770 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1771 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1772 if (hwAvSync) {
1773 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1774 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1775 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1776 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1777 }
1778 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1779 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1780 sinkConfig->config_mask |= config_mask;
1781 sourceConfig->config_mask |= config_mask;
1782 return NO_ERROR;
1783}
1784
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001785PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1786 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001787{
1788 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001789 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1790 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1791 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1792 if (deviceModule == nullptr) {
1793 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1794 return patchBuilder;
1795 }
1796 const InputProfileCollection inputProfiles = msdIsSource ?
1797 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1798 const OutputProfileCollection outputProfiles = msdIsSource ?
1799 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1800
1801 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1802 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1803 device : getMsdAudioOutDevices().itemAt(0);
1804 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1805
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001806 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1807 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001808 AudioProfileVector sourceProfiles;
1809 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001810 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1811 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001812 for (auto hwAvSync : { true, false }) {
1813 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1814 sourceProfiles, sinkProfiles) != NO_ERROR) {
1815 continue;
1816 }
1817 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1818 &sinkConfig) == NO_ERROR) {
1819 // Found a matching config. Re-create PatchBuilder with this config.
1820 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1821 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001822 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001823 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001824 " supporting PCM format conversion.", __func__);
1825 return patchBuilder;
1826}
1827
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001828status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001829 DeviceVector devices;
1830 if (outputDevices != nullptr && outputDevices->size() > 0) {
1831 devices.add(*outputDevices);
1832 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001833 // Use media strategy for unspecified output device. This should only
1834 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1835 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001836 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001837 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001838 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001839 }
Michael Chan6fb34492020-12-08 15:44:49 +11001840 std::vector<PatchBuilder> patchesToCreate;
1841 for (auto i = 0u; i < devices.size(); ++i) {
1842 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001843 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001844 }
1845 // Retain only the MSD patches associated with outputDevices request.
1846 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001847 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001848 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1849 auto retainedPatch = false;
1850 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1851 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1852 patchesToRemove.removeItemsAt(i);
1853 retainedPatch = true;
1854 break;
1855 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001856 }
Michael Chan6fb34492020-12-08 15:44:49 +11001857 if (retainedPatch) {
1858 it = patchesToCreate.erase(it);
1859 continue;
1860 }
1861 ++it;
1862 }
1863 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1864 return NO_ERROR;
1865 }
1866 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1867 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001868 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001869 }
Michael Chan6fb34492020-12-08 15:44:49 +11001870 status_t status = NO_ERROR;
1871 for (const auto &p : patchesToCreate) {
1872 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1873 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1874 char message[256];
1875 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1876 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1877 currStatus == NO_ERROR ? "Success" : "Error",
1878 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1879 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1880 if (currStatus == NO_ERROR) {
1881 ALOGD("%s", message);
1882 } else {
1883 ALOGE("%s", message);
1884 if (status == NO_ERROR) {
1885 status = currStatus;
1886 }
1887 }
1888 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001889 return status;
1890}
1891
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001892void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1893 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001894 for (size_t i = 0; i < msdPatches.size(); i++) {
1895 const auto& patch = msdPatches[i];
1896 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1897 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1898 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1899 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1900 releaseAudioPatch(patch->getHandle(), mUidCached);
1901 break;
1902 }
1903 }
1904 }
1905}
1906
Dorin Drimus94d94412022-02-02 09:05:02 +01001907bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1908 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1909 AudioPatchCollection msdPatches = getMsdOutputPatches();
1910 for (size_t i = 0; i < msdPatches.size(); i++) {
1911 const auto& patch = msdPatches[i];
1912 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1913 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1914 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1915 const auto& foundDevice = devicesToCheck.getDevice(
1916 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1917 if (foundDevice != nullptr) {
1918 devicesToCheck.remove(foundDevice);
1919 if (devicesToCheck.isEmpty()) {
1920 return true;
1921 }
1922 }
1923 }
1924 }
1925 }
1926 return false;
1927}
1928
Eric Laurente0720872014-03-11 09:30:41 -07001929audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001930 audio_output_flags_t flags,
1931 audio_format_t format,
1932 audio_channel_mask_t channelMask,
1933 uint32_t samplingRate,
1934 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001935{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001936 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1937 "%s called with format %#x", __func__, format);
1938
jiabinebb6af42020-06-09 17:31:17 -07001939 // Return the output that haptic-generating attached to when 1) session id is specified,
1940 // 2) haptic-generating effect exists for given session id and 3) the output that
1941 // haptic-generating effect attached to is in given outputs.
1942 if (sessionId != AUDIO_SESSION_NONE) {
1943 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1944 sessionId, FX_IID_HAPTICGENERATOR);
1945 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1946 return hapticGeneratingOutput;
1947 }
1948 }
1949
Eric Laurent16c66dd2019-05-01 17:54:10 -07001950 // Flags disqualifying an output: the match must happen before calling selectOutput()
1951 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1952 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1953
1954 // Flags expressing a functional request: must be honored in priority over
1955 // other criteria
1956 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1957 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001958 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1959 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001960 // Flags expressing a performance request: have lower priority than serving
1961 // requested sampling rate or channel mask
1962 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1963 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1964 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1965
1966 const audio_output_flags_t functionalFlags =
1967 (audio_output_flags_t)(flags & kFunctionalFlags);
1968 const audio_output_flags_t performanceFlags =
1969 (audio_output_flags_t)(flags & kPerformanceFlags);
1970
1971 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1972
Eric Laurente552edb2014-03-10 17:42:56 -07001973 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001974 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001975 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001976 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001977 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001978 // with tiebreak preferring the minimum number of extra functional flags
1979 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001980 // 3: the output supporting the exact channel mask
1981 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00001982 // 5: the output with the highest sampling rate if the requested sample rate is
1983 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001984 // 6: the output with the highest number of requested performance flags
1985 // 7: the output with the bit depth the closest to the requested one
1986 // 8: the primary output
1987 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001988
Eric Laurent16c66dd2019-05-01 17:54:10 -07001989 // matching criteria values in priority order for best matching output so far
1990 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001991
Eric Laurent16c66dd2019-05-01 17:54:10 -07001992 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1993 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1994 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001995
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001996 for (audio_io_handle_t output : outputs) {
1997 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001998 // matching criteria values in priority order for current output
1999 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002000
Eric Laurent16c66dd2019-05-01 17:54:10 -07002001 if (outputDesc->isDuplicated()) {
2002 continue;
2003 }
2004 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2005 continue;
2006 }
Eric Laurent8838a382014-09-08 16:44:28 -07002007
Eric Laurent16c66dd2019-05-01 17:54:10 -07002008 // If haptic channel is specified, use the haptic output if present.
2009 // When using haptic output, same audio format and sample rate are required.
2010 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002011 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002012 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2013 continue;
2014 }
2015 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002016 && format == outputDesc->getFormat()
2017 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002018 currentMatchCriteria[0] = outputHapticChannelCount;
2019 }
2020
2021 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002022 const int matchingFunctionalFlags =
2023 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2024 const int totalFunctionalFlags =
2025 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2026 // Prefer matching functional flags, but subtract unnecessary functional flags.
2027 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002028
2029 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002030 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2031 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002032 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2033 channelCount <= outputChannelCount) {
2034 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002035 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2036 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002037 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002038 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002039 currentMatchCriteria[3] = outputChannelCount;
2040 }
2041
2042 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002043 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002044 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002045 }
2046
2047 // performance flags match
2048 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2049
2050 // format match
2051 if (format != AUDIO_FORMAT_INVALID) {
2052 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002053 PolicyAudioPort::kFormatDistanceMax -
2054 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002055 }
2056
2057 // primary output match
2058 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2059
2060 // compare match criteria by priority then value
2061 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2062 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2063 bestMatchCriteria = currentMatchCriteria;
2064 bestOutput = output;
2065
2066 std::stringstream result;
2067 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2068 std::ostream_iterator<int>(result, " "));
2069 ALOGV("%s new bestOutput %d criteria %s",
2070 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002071 }
2072 }
2073
Eric Laurent16c66dd2019-05-01 17:54:10 -07002074 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002075}
2076
Eric Laurent8fc147b2018-07-22 19:13:55 -07002077status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002078{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002079 ALOGV("%s portId %d", __FUNCTION__, portId);
2080
2081 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2082 if (outputDesc == 0) {
2083 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002084 return BAD_VALUE;
2085 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002086 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002087
Eric Laurent8fc147b2018-07-22 19:13:55 -07002088 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002089 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002090
Eric Laurent733ce942017-12-07 12:18:25 -08002091 status_t status = outputDesc->start();
2092 if (status != NO_ERROR) {
2093 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002094 }
2095
Eric Laurent97ac8712018-07-27 18:59:02 -07002096 uint32_t delayMs;
2097 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002098
2099 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002100 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002101 if (status == DEAD_OBJECT) {
2102 sp<SwAudioOutputDescriptor> desc =
2103 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2104 if (desc == nullptr) {
2105 // This is not common, it may indicate something wrong with the HAL.
2106 ALOGE("%s unable to open output with default config", __func__);
2107 return status;
2108 }
2109 desc->mUsePreferredMixerAttributes = true;
2110 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002111 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002112 }
jiabina84c3d32022-12-02 18:59:55 +00002113
2114 // If the client is the first one active on preferred mixer parameters, reopen the output
2115 // if the current mixer parameters doesn't match the preferred one.
2116 if (outputDesc->devices().size() == 1) {
2117 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2118 outputDesc->devices()[0]->getId(), client->strategy());
2119 if (info != nullptr && info->getUid() == client->uid()) {
2120 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2121 info->getConfigBase(), info->getFlags())) {
2122 stopSource(outputDesc, client);
2123 outputDesc->stop();
2124 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2125 config.channel_mask = info->getConfigBase().channel_mask;
2126 config.sample_rate = info->getConfigBase().sample_rate;
2127 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002128 sp<SwAudioOutputDescriptor> desc =
2129 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2130 if (desc == nullptr) {
2131 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002132 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002133 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002134 // Intentionally return error to let the client side resending request for
2135 // creating and starting.
2136 return DEAD_OBJECT;
2137 }
2138 info->increaseActiveClient();
2139 }
2140 }
2141
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002142 if (client->hasPreferredDevice()) {
2143 // playback activity with preferred device impacts routing occurred, inform upper layers
2144 mpClientInterface->onRoutingUpdated();
2145 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002146 if (delayMs != 0) {
2147 usleep(delayMs * 1000);
2148 }
2149
2150 return status;
2151}
2152
Eric Laurent96d1dda2022-03-14 17:14:19 +01002153bool AudioPolicyManager::isLeUnicastActive() const {
2154 if (isInCall()) {
2155 return true;
2156 }
2157 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2158}
2159
2160bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2161 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2162 return false;
2163 }
2164 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2165 ALOGV("%s active %d", __func__, active);
2166 return active;
2167}
2168
Eric Laurent97ac8712018-07-27 18:59:02 -07002169status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2170 const sp<TrackClientDescriptor>& client,
2171 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002172{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002173 // cannot start playback of STREAM_TTS if any other output is being used
2174 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002175
2176 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002177 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002178 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002179 auto clientStrategy = client->strategy();
2180 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002181 if (stream == AUDIO_STREAM_TTS) {
2182 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002183 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002184 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002185 return INVALID_OPERATION;
2186 } else {
2187 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2188 }
2189 } else {
2190 // some playback other than beacon starts
2191 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2192 }
2193
Eric Laurent77305a62016-07-25 16:39:22 -07002194 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002195 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002196 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002197
François Gaffie11d30102018-11-02 16:09:09 +01002198 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002199 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002200 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002201 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002202 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002203 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002204 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002205 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002206 } else {
2207 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002208 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002209 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2210 AUDIO_FORMAT_DEFAULT);
2211 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2212 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002213 }
2214
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002215 // requiresMuteCheck is false when we can bypass mute strategy.
2216 // It covers a common case when there is no materially active audio
2217 // and muting would result in unnecessary delay and dropped audio.
2218 const uint32_t outputLatencyMs = outputDesc->latency();
2219 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002220 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002221
Eric Laurente552edb2014-03-10 17:42:56 -07002222 // increment usage count for this stream on the requested output:
2223 // NOTE that the usage count is the same for duplicated output and hardware output which is
2224 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002225 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002226
2227 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002228 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2229 client->isPreferredDeviceForExclusiveUse()) {
2230 // Preferred device may be exclusive, use only if no other active clients on this output
2231 devices = DeviceVector(
2232 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2233 } else {
2234 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2235 }
François Gaffie11d30102018-11-02 16:09:09 +01002236 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002237 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002238 }
2239 }
Eric Laurente552edb2014-03-10 17:42:56 -07002240
François Gaffiec005e562018-11-06 15:04:49 +01002241 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002242 selectOutputForMusicEffects();
2243 }
2244
François Gaffie1c878552018-11-22 16:53:21 +01002245 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002246 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002247 if (devices.isEmpty()) {
2248 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002249 }
François Gaffiec005e562018-11-06 15:04:49 +01002250 bool shouldWait =
2251 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2252 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2253 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002254 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002255 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002256 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002257 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002258 // An output has a shared device if
2259 // - managed by the same hw module
2260 // - supports the currently selected device
2261 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002262 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002263
Eric Laurent77305a62016-07-25 16:39:22 -07002264 // force a device change if any other output is:
2265 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002266 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002267 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002268 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002269 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002270 // change the device currently selected by the other output.
2271 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002272 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002273 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002274 force = true;
2275 }
2276 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002277 // a notification so that audio focus effect can propagate, or that a mute/unmute
2278 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002279 const uint32_t latencyMs = desc->latency();
2280 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2281
2282 if (shouldWait && isActive && (waitMs < latencyMs)) {
2283 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002284 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002285
2286 // Require mute check if another output is on a shared device
2287 // and currently active to have proper drain and avoid pops.
2288 // Note restoring AudioTracks onto this output needs to invoke
2289 // a volume ramp if there is no mute.
2290 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002291 }
2292 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002293
jiabin3ff8d7d2022-12-13 06:27:44 +00002294 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2295 // If the output is open with preferred mixer attributes, but the routed device is
2296 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2297 // changed.
2298 return DEAD_OBJECT;
2299 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002300 const uint32_t muteWaitMs =
jiabin3ff8d7d2022-12-13 06:27:44 +00002301 setOutputDevices(outputDesc, devices, force, 0, nullptr, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002302
Eric Laurente552edb2014-03-10 17:42:56 -07002303 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002304 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002305 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002306 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002307 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002308 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002309 outputDesc->useHwGain() /*force*/)) {
2310 // request AudioService to reinitialize the volume curves asynchronously
2311 ALOGE("checkAndSetVolume failed, requesting volume range init");
2312 mpClientInterface->onVolumeRangeInitRequest();
2313 };
Eric Laurente552edb2014-03-10 17:42:56 -07002314
2315 // update the outputs if starting an output with a stream that can affect notification
2316 // routing
2317 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002318
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002319 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002320 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002321 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002322 }
Eric Laurentdc462862016-07-19 12:29:53 -07002323
2324 if (waitMs > muteWaitMs) {
2325 *delayMs = waitMs - muteWaitMs;
2326 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002327
2328 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2329 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2330 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2331 // change occurs after the MixerThread starts and causes a stream volume
2332 // glitch.
2333 //
2334 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002335 }
Eric Laurentdc462862016-07-19 12:29:53 -07002336
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002337 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002338 mEngine->getForceUse(
2339 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002340 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002341 }
2342
Eric Laurent97ac8712018-07-27 18:59:02 -07002343 // Automatically enable the remote submix input when output is started on a re routing mix
2344 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002345 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2346 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002347 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2348 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2349 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002350 "remote-submix",
2351 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002352 }
2353
Eric Laurent96d1dda2022-03-14 17:14:19 +01002354 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2355
Eric Laurente552edb2014-03-10 17:42:56 -07002356 return NO_ERROR;
2357}
2358
Eric Laurent96d1dda2022-03-14 17:14:19 +01002359void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2360 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2361 bool isUnicastActive = isLeUnicastActive();
2362
2363 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002364 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002365 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2366 for (size_t i = 0; i < mOutputs.size(); i++) {
2367 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2368 if (desc != ignoredOutput && desc->isActive()
2369 && ((isUnicastActive &&
2370 !desc->devices().
2371 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2372 || (wasUnicastActive &&
2373 !desc->devices().getDevicesFromTypes(
2374 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2375 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2376 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002377 if (desc->mUsePreferredMixerAttributes && force) {
2378 // If the device is using preferred mixer attributes, the output need to reopen
2379 // with default configuration when the new selected devices are different from
2380 // current routing devices.
2381 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2382 continue;
2383 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002384 setOutputDevices(desc, newDevices, force, delayMs);
2385 // re-apply device specific volume if not done by setOutputDevice()
2386 if (!force) {
2387 applyStreamVolumes(desc, newDevices.types(), delayMs);
2388 }
2389 }
2390 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002391 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002392 }
2393}
2394
Eric Laurent8fc147b2018-07-22 19:13:55 -07002395status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002396{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002397 ALOGV("%s portId %d", __FUNCTION__, portId);
2398
2399 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2400 if (outputDesc == 0) {
2401 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002402 return BAD_VALUE;
2403 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002404 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002405
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002406 if (client->hasPreferredDevice(true)) {
2407 // playback activity with preferred device impacts routing occurred, inform upper layers
2408 mpClientInterface->onRoutingUpdated();
2409 }
2410
Eric Laurent97ac8712018-07-27 18:59:02 -07002411 ALOGV("stopOutput() output %d, stream %d, session %d",
2412 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002413
Eric Laurent97ac8712018-07-27 18:59:02 -07002414 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002415
Eric Laurent733ce942017-12-07 12:18:25 -08002416 if (status == NO_ERROR ) {
2417 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002418 } else {
2419 return status;
2420 }
2421
2422 if (outputDesc->devices().size() == 1) {
2423 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2424 outputDesc->devices()[0]->getId(), client->strategy());
2425 if (info != nullptr && info->getUid() == client->uid()) {
2426 info->decreaseActiveClient();
2427 if (info->getActiveClientCount() == 0) {
2428 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2429 }
2430 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002431 }
2432 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002433}
2434
Eric Laurent97ac8712018-07-27 18:59:02 -07002435status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2436 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002437{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002438 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002439 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002440 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002441 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002442
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002443 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2444
François Gaffie1c878552018-11-22 16:53:21 +01002445 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2446 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002447 // Automatically disable the remote submix input when output is stopped on a
2448 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002449 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002450 if (isSingleDeviceType(
2451 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002452 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002453 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002454 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2455 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002456 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002457 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002458 }
2459 }
2460 bool forceDeviceUpdate = false;
2461 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002462 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002463 forceDeviceUpdate = true;
2464 }
2465
Eric Laurente552edb2014-03-10 17:42:56 -07002466 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002467 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002468
Eric Laurente552edb2014-03-10 17:42:56 -07002469 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002470 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002471 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002472 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002473
2474 // If the routing does not change, if an output is routed on a device using HwGain
2475 // (aka setAudioPortConfig) and there are still active clients following different
2476 // volume group(s), force reapply volume
2477 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2478 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2479
Eric Laurente552edb2014-03-10 17:42:56 -07002480 // delay the device switch by twice the latency because stopOutput() is executed when
2481 // the track stop() command is received and at that time the audio track buffer can
2482 // still contain data that needs to be drained. The latency only covers the audio HAL
2483 // and kernel buffers. Also the latency does not always include additional delay in the
2484 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002485 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2486 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002487
2488 // force restoring the device selection on other active outputs if it differs from the
2489 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002490 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002491 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002492 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002493 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002494 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002495 desc->isActive() &&
2496 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002497 (newDevices != desc->devices())) {
2498 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2499 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002500
jiabin3ff8d7d2022-12-13 06:27:44 +00002501 if (desc->mUsePreferredMixerAttributes && force) {
2502 // If the device is using preferred mixer attributes, the output need to
2503 // reopen with default configuration when the new selected devices are
2504 // different from current routing devices.
2505 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2506 continue;
2507 }
François Gaffie11d30102018-11-02 16:09:09 +01002508 setOutputDevices(desc, newDevices2, force, delayMs);
2509
Eric Laurent57de36c2016-09-28 16:59:11 -07002510 // re-apply device specific volume if not done by setOutputDevice()
2511 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002512 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002513 }
Eric Laurente552edb2014-03-10 17:42:56 -07002514 }
2515 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002516 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002517 // update the outputs if stopping one with a stream that can affect notification routing
2518 handleNotificationRoutingForStream(stream);
2519 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002520
2521 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2522 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002523 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002524 }
2525
François Gaffiec005e562018-11-06 15:04:49 +01002526 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002527 selectOutputForMusicEffects();
2528 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002529
2530 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2531
Eric Laurente552edb2014-03-10 17:42:56 -07002532 return NO_ERROR;
2533 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002534 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002535 return INVALID_OPERATION;
2536 }
2537}
2538
jiabinbce0c1d2020-10-05 11:20:18 -07002539bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002540{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002541 ALOGV("%s portId %d", __FUNCTION__, portId);
2542
2543 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2544 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002545 // If an output descriptor is closed due to a device routing change,
2546 // then there are race conditions with releaseOutput from tracks
2547 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2548 // destroyed shortly thereafter.
2549 //
2550 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002551 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002552 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002553 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002554
2555 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002556
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302557 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2558 if (outputDesc->isClientActive(client)) {
2559 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2560 stopOutput(portId);
2561 }
2562
Eric Laurent8fc147b2018-07-22 19:13:55 -07002563 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2564 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002565 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002566 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002567 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002568 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002569 if (--outputDesc->mDirectOpenCount == 0) {
2570 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002571 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002572 }
2573 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302574
Andy Hung39efb7a2018-09-26 15:39:28 -07002575 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002576 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2577 // The output is pending reopened to query dynamic profiles and
2578 // there is no active clients
2579 closeOutput(outputDesc->mIoHandle);
2580 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2581 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2582 if (newOutputDesc == nullptr) {
2583 ALOGE("%s failed to open output", __func__);
2584 }
2585 return true;
2586 }
2587 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002588}
2589
Eric Laurentcaf7f482014-11-25 17:50:47 -08002590status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2591 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002592 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002593 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002594 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002595 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002596 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002597 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002598 input_type_t *inputType,
2599 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002600{
François Gaffiec005e562018-11-06 15:04:49 +01002601 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002602 "flags %#x attributes=%s requested device ID %d",
2603 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2604 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002605
Eric Laurentad2e7b92017-09-14 20:06:42 -07002606 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002607 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002608 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002609 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002610 sp<AudioInputDescriptor> inputDesc;
2611 sp<RecordClientDescriptor> clientDesc;
2612 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002613 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002614 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002615
2616 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2617 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2618 return INVALID_OPERATION;
2619 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002620
Francois Gaffie716e1432019-01-14 16:58:59 +01002621 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2622 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002623 }
2624
Paul McLean466dc8e2015-04-17 13:15:36 -06002625 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002626 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002627 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002628
Eric Laurentad2e7b92017-09-14 20:06:42 -07002629 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2630 // possible
2631 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2632 *input != AUDIO_IO_HANDLE_NONE) {
2633 ssize_t index = mInputs.indexOfKey(*input);
2634 if (index < 0) {
2635 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2636 status = BAD_VALUE;
2637 goto error;
2638 }
2639 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002640 RecordClientVector clients = inputDesc->getClientsForSession(session);
2641 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002642 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2643 status = BAD_VALUE;
2644 goto error;
2645 }
2646 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2647 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002648 // corresponds to a new client and is only permitted from the same UID.
2649 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002650 if (clients.size() > 1) {
2651 for (const auto& client : clients) {
2652 // The client map is ordered by key values (portId) and portIds are allocated
2653 // incrementaly. So the first client in this list is the one opened by audio flinger
2654 // when the mmap stream is created and should be ignored as it does not correspond
2655 // to an actual client
2656 if (client == *clients.cbegin()) {
2657 continue;
2658 }
2659 if (uid != client->uid() && !client->isSilenced()) {
2660 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2661 uid, client->portId(), client->uid());
2662 status = INVALID_OPERATION;
2663 goto error;
2664 }
Eric Laurent331679c2018-04-16 17:03:16 -07002665 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002666 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002667 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002668 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002669
Eric Laurentfecbceb2021-02-09 14:46:43 +01002670 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002671 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002672 }
2673
2674 *input = AUDIO_IO_HANDLE_NONE;
2675 *inputType = API_INPUT_INVALID;
2676
Francois Gaffie716e1432019-01-14 16:58:59 +01002677 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002678 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002679 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002680 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002681 ALOGW("%s could not find input mix for attr %s",
2682 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002683 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002684 }
jiabinc1de2df2019-05-07 14:26:40 -07002685 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2686 String8(attr->tags + strlen("addr=")),
2687 AUDIO_FORMAT_DEFAULT);
2688 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002689 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002690 __func__, attributes.source, attributes.tags);
2691 status = BAD_VALUE;
2692 goto error;
2693 }
2694
Kevin Rocard25f9b052019-02-27 15:08:54 -08002695 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2696 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2697 } else {
2698 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2699 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002700 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002701 if (explicitRoutingDevice != nullptr) {
2702 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002703 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002704 // Prevent from storing invalid requested device id in clients
2705 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002706 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002707 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2708 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002709 }
François Gaffie11d30102018-11-02 16:09:09 +01002710 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002711 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002712 status = BAD_VALUE;
2713 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002714 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002715 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2716 *inputType = API_INPUT_MIX_CAPTURE;
2717 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002718 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2719 // there is an external policy, but this input is attached to a mix of recorders,
2720 // meaning it receives audio injected into the framework, so the recorder doesn't
2721 // know about it and is therefore considered "legacy"
2722 *inputType = API_INPUT_LEGACY;
2723 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002724 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002725 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002726 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002727 } else {
2728 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002729 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002730
Eric Laurent599c7582015-12-07 18:05:55 -08002731 }
2732
François Gaffiec005e562018-11-06 15:04:49 +01002733 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002734 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002735 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002736 AudioProfileVector profiles;
2737 status_t ret = getProfilesForDevices(
2738 DeviceVector(device), profiles, flags, true /*isInput*/);
2739 if (ret == NO_ERROR && !profiles.empty()) {
2740 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
2741 : *profiles[0]->getChannels().begin();
2742 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
2743 : *profiles[0]->getSampleRates().begin();
2744 config->format = profiles[0]->getFormat();
2745 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002746 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002747 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002748
Eric Laurent8f42ea12018-08-08 09:08:25 -07002749exit:
2750
François Gaffiec005e562018-11-06 15:04:49 +01002751 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2752 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002753
Francois Gaffie716e1432019-01-14 16:58:59 +01002754 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002755 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002756 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002757
Mikhail Naganov2996f672019-04-18 12:29:59 -07002758 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002759 requestedDeviceId, attributes.source, flags,
2760 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002761 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002762 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002763
2764 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2765 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002766
Eric Laurent599c7582015-12-07 18:05:55 -08002767 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002768
2769error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002770 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002771}
2772
2773
François Gaffie11d30102018-11-02 16:09:09 +01002774audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002775 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002776 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002777 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002778 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002779 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002780{
2781 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002782 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002783 bool isSoundTrigger = false;
2784
François Gaffiec005e562018-11-06 15:04:49 +01002785 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002786 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2787 if (index >= 0) {
2788 input = mSoundTriggerSessions.valueFor(session);
2789 isSoundTrigger = true;
2790 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2791 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2792 } else {
2793 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002794 }
François Gaffiec005e562018-11-06 15:04:49 +01002795 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002796 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002797 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002798 }
2799
Carter Hsua3abb402021-10-26 11:11:20 +08002800 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2801 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2802 }
2803
Eric Laurentfe231122017-11-17 17:48:06 -08002804 // sampling rate and flags may be updated by getInputProfile
2805 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2806 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002807 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002808 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002809 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002810 // find a compatible input profile (not necessarily identical in parameters)
2811 sp<IOProfile> profile = getInputProfile(
2812 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2813 if (profile == nullptr) {
2814 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002815 }
jiabin2fd710d2022-05-02 23:20:22 +00002816
Glenn Kasten05ddca52016-02-11 08:17:12 -08002817 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002818 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002819 if (samplingRate == 0) {
2820 samplingRate = profileSamplingRate;
2821 }
Eric Laurente552edb2014-03-10 17:42:56 -07002822
Eric Laurent322b4d22015-04-03 15:57:54 -07002823 if (profile->getModuleHandle() == 0) {
2824 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002825 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002826 }
2827
Eric Laurentec376dc2021-04-08 20:41:22 +02002828 // Reuse an already opened input if a client with the same session ID already exists
2829 // on that input
2830 for (size_t i = 0; i < mInputs.size(); i++) {
2831 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2832 if (desc->mProfile != profile) {
2833 continue;
2834 }
2835 RecordClientVector clients = desc->clientsList();
2836 for (const auto &client : clients) {
2837 if (session == client->session()) {
2838 return desc->mIoHandle;
2839 }
2840 }
2841 }
2842
Eric Laurent3974e3b2017-12-07 17:58:43 -08002843 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002844 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002845 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002846 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002847 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002848 continue;
2849 }
2850 // if sound trigger, reuse input if used by other sound trigger on same session
2851 // else
2852 // reuse input if active client app is not in IDLE state
2853 //
2854 RecordClientVector clients = desc->clientsList();
2855 bool doClose = false;
2856 for (const auto& client : clients) {
2857 if (isSoundTrigger != client->isSoundTrigger()) {
2858 continue;
2859 }
2860 if (client->isSoundTrigger()) {
2861 if (session == client->session()) {
2862 return desc->mIoHandle;
2863 }
2864 continue;
2865 }
2866 if (client->active() && client->appState() != APP_STATE_IDLE) {
2867 return desc->mIoHandle;
2868 }
2869 doClose = true;
2870 }
2871 if (doClose) {
2872 closeInput(desc->mIoHandle);
2873 } else {
2874 i++;
2875 }
2876 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002877 }
2878
Eric Laurentfe231122017-11-17 17:48:06 -08002879 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002880
Eric Laurentfe231122017-11-17 17:48:06 -08002881 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2882 lConfig.sample_rate = profileSamplingRate;
2883 lConfig.channel_mask = profileChannelMask;
2884 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002885
François Gaffie11d30102018-11-02 16:09:09 +01002886 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002887
2888 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002889 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002890 (profileSamplingRate != lConfig.sample_rate) ||
2891 !audio_formats_match(profileFormat, lConfig.format) ||
2892 (profileChannelMask != lConfig.channel_mask)) {
2893 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002894 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002895 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002896 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002897 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002898 }
Eric Laurent599c7582015-12-07 18:05:55 -08002899 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002900 }
2901
Eric Laurentc722f302014-12-10 11:21:49 -08002902 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002903
Eric Laurent599c7582015-12-07 18:05:55 -08002904 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002905 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002906
Eric Laurent599c7582015-12-07 18:05:55 -08002907 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002908}
2909
Eric Laurent4eb58f12018-12-07 16:41:02 -08002910status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002911{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002912 ALOGV("%s portId %d", __FUNCTION__, portId);
2913
2914 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2915 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002916 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002917 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002918 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002919 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002920 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002921 if (client->active()) {
2922 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2923 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002924 }
2925
Eric Laurent8f42ea12018-08-08 09:08:25 -07002926 audio_session_t session = client->session();
2927
Eric Laurent4eb58f12018-12-07 16:41:02 -08002928 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002929
Eric Laurent4eb58f12018-12-07 16:41:02 -08002930 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002931
Eric Laurent4eb58f12018-12-07 16:41:02 -08002932 status_t status = inputDesc->start();
2933 if (status != NO_ERROR) {
2934 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002935 }
Eric Laurente552edb2014-03-10 17:42:56 -07002936
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002937 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002938 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002939 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002940
Eric Laurent8f42ea12018-08-08 09:08:25 -07002941 // indicate active capture to sound trigger service if starting capture from a mic on
2942 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002943 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002944 if (device != nullptr) {
2945 status = setInputDevice(input, device, true /* force */);
2946 } else {
2947 ALOGW("%s no new input device can be found for descriptor %d",
2948 __FUNCTION__, inputDesc->getId());
2949 status = BAD_VALUE;
2950 }
Eric Laurente552edb2014-03-10 17:42:56 -07002951
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002952 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002953 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002954 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002955 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002956 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2957 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002958 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002959 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002960
François Gaffie11d30102018-11-02 16:09:09 +01002961 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2962 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002963 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002964 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002965 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002966
Eric Laurent8f42ea12018-08-08 09:08:25 -07002967 // automatically enable the remote submix output when input is started if not
2968 // used by a policy mix of type MIX_TYPE_RECORDERS
2969 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002970 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002971 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002972 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002973 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002974 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2975 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002976 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002977 if (address != "") {
2978 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2979 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002980 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002981 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002982 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002983 } else if (status != NO_ERROR) {
2984 // Restore client activity state.
2985 inputDesc->setClientActive(client, false);
2986 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002987 }
2988
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002989 ALOGV("%s input %d source = %d status = %d exit",
2990 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002991
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002992 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002993}
2994
Eric Laurent8fc147b2018-07-22 19:13:55 -07002995status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002996{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002997 ALOGV("%s portId %d", __FUNCTION__, portId);
2998
2999 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3000 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003001 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003002 return BAD_VALUE;
3003 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003004 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003005 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003006 if (!client->active()) {
3007 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003008 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003009 }
Carter Hsue6139d52021-07-08 10:30:20 +08003010 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003011 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003012
Eric Laurent8f42ea12018-08-08 09:08:25 -07003013 inputDesc->stop();
3014 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003015 auto current_source = inputDesc->source();
3016 setInputDevice(input, getNewInputDevice(inputDesc),
3017 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003018 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003019 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003020 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003021 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003022 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3023 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003024 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003025 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003026
3027 // automatically disable the remote submix output when input is stopped if not
3028 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003029 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003030 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003031 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003032 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003033 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3034 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003035 }
3036 if (address != "") {
3037 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3038 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003039 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003040 }
3041 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003042 resetInputDevice(input);
3043
3044 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3045 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003046 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3047 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003048 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003049 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003050 }
3051 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003052 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003053 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003054}
3055
Eric Laurent8fc147b2018-07-22 19:13:55 -07003056void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003057{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003058 ALOGV("%s portId %d", __FUNCTION__, portId);
3059
3060 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3061 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003062 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003063 return;
3064 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003065 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003066 audio_io_handle_t input = inputDesc->mIoHandle;
3067
Eric Laurent8f42ea12018-08-08 09:08:25 -07003068 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003069
Andy Hung39efb7a2018-09-26 15:39:28 -07003070 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08003071
Andy Hung39efb7a2018-09-26 15:39:28 -07003072 if (inputDesc->getClientCount() > 0) {
3073 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003074 return;
3075 }
3076
Eric Laurent05b90f82014-08-27 15:32:29 -07003077 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003078 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003079 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003080}
3081
Eric Laurent8f42ea12018-08-08 09:08:25 -07003082void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003083{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003084 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003085
3086 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003087 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003088 }
3089}
3090
Eric Laurent8f42ea12018-08-08 09:08:25 -07003091void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3092{
3093 stopInput(portId);
3094 releaseInput(portId);
3095}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003096
Eric Laurent0dd51852019-04-19 18:18:58 -07003097void AudioPolicyManager::checkCloseInputs() {
3098 // After connecting or disconnecting an input device, close input if:
3099 // - it has no client (was just opened to check profile) OR
3100 // - none of its supported devices are connected anymore OR
3101 // - one of its clients cannot be routed to one of its supported
3102 // devices anymore. Otherwise update device selection
3103 std::vector<audio_io_handle_t> inputsToClose;
3104 for (size_t i = 0; i < mInputs.size(); i++) {
3105 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3106 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003107 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003108 inputsToClose.push_back(mInputs.keyAt(i));
3109 } else {
3110 bool close = false;
3111 for (const auto& client : input->clientsList()) {
3112 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003113 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3114 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003115 if (!input->supportedDevices().contains(device)) {
3116 close = true;
3117 break;
3118 }
3119 }
3120 if (close) {
3121 inputsToClose.push_back(mInputs.keyAt(i));
3122 } else {
3123 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3124 }
3125 }
3126 }
3127
3128 for (const audio_io_handle_t handle : inputsToClose) {
3129 ALOGV("%s closing input %d", __func__, handle);
3130 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003131 }
Eric Laurentd4692962014-05-05 18:13:44 -07003132}
3133
François Gaffie251c7f02018-11-07 10:41:08 +01003134void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003135{
3136 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003137 if (indexMin < 0 || indexMax < 0) {
3138 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3139 return;
3140 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003141 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003142
3143 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003144 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3145 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003146 continue;
3147 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003148 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003149 }
Eric Laurente552edb2014-03-10 17:42:56 -07003150}
3151
Eric Laurente0720872014-03-11 09:30:41 -07003152status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003153 int index,
3154 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003155{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003156 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003157 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3158 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3159 return NO_ERROR;
3160 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003161 ALOGV("%s: stream %s attributes=%s", __func__,
3162 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003163 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003164}
3165
Eric Laurente0720872014-03-11 09:30:41 -07003166status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003167 int *index,
3168 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003169{
François Gaffiec005e562018-11-06 15:04:49 +01003170 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3171 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003172 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003173 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003174 deviceTypes = mEngine->getOutputDevicesForStream(
3175 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003176 }
jiabin9a3361e2019-10-01 09:38:30 -07003177 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003178}
3179
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003180status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003181 int index,
3182 audio_devices_t device)
3183{
3184 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003185 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3186 if (group == VOLUME_GROUP_NONE) {
3187 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003188 return BAD_VALUE;
3189 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003190 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003191 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003192 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003193 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003194 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3195 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3196 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3197 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003198 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3199
3200 status = setVolumeCurveIndex(index, device, curves);
3201 if (status != NO_ERROR) {
3202 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3203 return status;
3204 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003205
jiabin9a3361e2019-10-01 09:38:30 -07003206 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003207 auto curCurvAttrs = curves.getAttributes();
3208 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3209 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003210 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003211 } else if (!curves.getStreamTypes().empty()) {
3212 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003213 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003214 } else {
3215 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3216 return BAD_VALUE;
3217 }
jiabin9a3361e2019-10-01 09:38:30 -07003218 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3219 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003220
François Gaffiecfe17322018-11-07 13:41:29 +01003221 // update volume on all outputs and streams matching the following:
3222 // - The requested stream (or a stream matching for volume control) is active on the output
3223 // - The device (or devices) selected by the engine for this stream includes
3224 // the requested device
3225 // - For non default requested device, currently selected device on the output is either the
3226 // requested device or one of the devices selected by the engine for this stream
3227 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3228 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003229 for (size_t i = 0; i < mOutputs.size(); i++) {
3230 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003231 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003232
jiabin9a3361e2019-10-01 09:38:30 -07003233 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3234 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003235 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003236
3237 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003238 continue;
3239 }
3240 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3241 curDevices.find(device) == curDevices.end()) {
3242 continue;
3243 }
3244 bool applyVolume = false;
3245 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3246 curSrcDevices.insert(device);
3247 applyVolume = (curSrcDevices.find(
3248 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3249 } else {
3250 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3251 }
3252 if (!applyVolume) {
3253 continue; // next output
3254 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003255 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3256 // If a higher priority strategy is active, and the output is routed to a device with a
3257 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003258 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003259 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003260 // If the volume source is active with higher priority source, ensure at least Sw Muted
3261 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003262 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3263 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3264 false /*preferredDevice*/);
3265 if (activeClients.empty()) {
3266 continue;
3267 }
3268 bool isPreempted = false;
3269 bool isHigherPriority = productStrategy < strategy;
3270 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003271 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003272 ALOGV("%s: Strategy=%d (\nrequester:\n"
3273 " group %d, volumeGroup=%d attributes=%s)\n"
3274 " higher priority source active:\n"
3275 " volumeGroup=%d attributes=%s) \n"
3276 " on output %zu, bailing out", __func__, productStrategy,
3277 group, group, toString(attributes).c_str(),
3278 client->volumeSource(), toString(client->attributes()).c_str(), i);
3279 applyVolume = false;
3280 isPreempted = true;
3281 break;
3282 }
3283 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003284 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003285 applyVolume = true;
3286 }
3287 }
3288 if (isPreempted || applyVolume) {
3289 break;
3290 }
3291 }
3292 if (!applyVolume) {
3293 continue; // next output
3294 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003295 }
François Gaffieed91f582020-01-31 10:35:37 +01003296 //FIXME: workaround for truncated touch sounds
3297 // delayed volume change for system stream to be removed when the problem is
3298 // handled by system UI
3299 status_t volStatus = checkAndSetVolume(
3300 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003301 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003302 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3303 if (volStatus != NO_ERROR) {
3304 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003305 }
3306 }
François Gaffiecfe17322018-11-07 13:41:29 +01003307 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3308 return status;
3309}
3310
François Gaffieaaac0fd2018-11-22 17:56:39 +01003311status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003312 audio_devices_t device,
3313 IVolumeCurves &volumeCurves)
3314{
3315 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3316 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003317 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3318 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003319 (index > volumeCurves.getVolumeIndexMax())) {
3320 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3321 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3322 return BAD_VALUE;
3323 }
3324 if (!audio_is_output_device(device)) {
3325 return BAD_VALUE;
3326 }
3327
3328 // Force max volume if stream cannot be muted
3329 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3330
François Gaffieaaac0fd2018-11-22 17:56:39 +01003331 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003332 volumeCurves.addCurrentVolumeIndex(device, index);
3333 return NO_ERROR;
3334}
3335
3336status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3337 int &index,
3338 audio_devices_t device)
3339{
3340 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3341 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003342 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003343 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003344 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003345 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003346 }
jiabin9a3361e2019-10-01 09:38:30 -07003347 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003348}
3349
3350status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3351 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003352 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003353{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003354 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003355 return BAD_VALUE;
3356 }
jiabin9a3361e2019-10-01 09:38:30 -07003357 index = curves.getVolumeIndex(deviceTypes);
3358 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003359 return NO_ERROR;
3360}
3361
3362status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3363 int &index)
3364{
3365 index = getVolumeCurves(attr).getVolumeIndexMin();
3366 return NO_ERROR;
3367}
3368
3369status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3370 int &index)
3371{
3372 index = getVolumeCurves(attr).getVolumeIndexMax();
3373 return NO_ERROR;
3374}
3375
Eric Laurent36829f92017-04-07 19:04:42 -07003376audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003377{
3378 // select one output among several suitable for global effects.
3379 // The priority is as follows:
3380 // 1: An offloaded output. If the effect ends up not being offloadable,
3381 // AudioFlinger will invalidate the track and the offloaded output
3382 // will be closed causing the effect to be moved to a PCM output.
3383 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003384 // 3: The primary output
3385 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003386
François Gaffiec005e562018-11-06 15:04:49 +01003387 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3388 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003389 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003390
Eric Laurent36829f92017-04-07 19:04:42 -07003391 if (outputs.size() == 0) {
3392 return AUDIO_IO_HANDLE_NONE;
3393 }
Eric Laurente552edb2014-03-10 17:42:56 -07003394
Eric Laurent36829f92017-04-07 19:04:42 -07003395 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3396 bool activeOnly = true;
3397
3398 while (output == AUDIO_IO_HANDLE_NONE) {
3399 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3400 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3401 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3402
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003403 for (audio_io_handle_t output : outputs) {
3404 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003405 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003406 continue;
3407 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003408 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3409 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003410 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003411 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003412 }
3413 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003414 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003415 }
3416 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003417 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003418 }
3419 }
3420 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3421 output = outputOffloaded;
3422 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3423 output = outputDeepBuffer;
3424 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3425 output = outputPrimary;
3426 } else {
3427 output = outputs[0];
3428 }
3429 activeOnly = false;
3430 }
3431
3432 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003433 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003434 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3435 mMusicEffectOutput = output;
3436 }
3437
3438 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003439 return output;
3440}
3441
Eric Laurent36829f92017-04-07 19:04:42 -07003442audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3443{
3444 return selectOutputForMusicEffects();
3445}
3446
Eric Laurente0720872014-03-11 09:30:41 -07003447status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003448 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003449 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003450 int session,
3451 int id)
3452{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003453 if (session != AUDIO_SESSION_DEVICE) {
3454 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003455 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003456 index = mInputs.indexOfKey(io);
3457 if (index < 0) {
3458 ALOGW("registerEffect() unknown io %d", io);
3459 return INVALID_OPERATION;
3460 }
Eric Laurente552edb2014-03-10 17:42:56 -07003461 }
3462 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003463 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3464 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3465 || strategy == PRODUCT_STRATEGY_NONE));
3466 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003467}
3468
Eric Laurentc241b0d2018-11-28 09:08:49 -08003469status_t AudioPolicyManager::unregisterEffect(int id)
3470{
3471 if (mEffects.getEffect(id) == nullptr) {
3472 return INVALID_OPERATION;
3473 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003474 if (mEffects.isEffectEnabled(id)) {
3475 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3476 setEffectEnabled(id, false);
3477 }
3478 return mEffects.unregisterEffect(id);
3479}
3480
3481status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3482{
3483 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3484 if (effect == nullptr) {
3485 return INVALID_OPERATION;
3486 }
3487
3488 status_t status = mEffects.setEffectEnabled(id, enabled);
3489 if (status == NO_ERROR) {
3490 mInputs.trackEffectEnabled(effect, enabled);
3491 }
3492 return status;
3493}
3494
Eric Laurent6c796322019-04-09 14:13:17 -07003495
3496status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3497{
3498 mEffects.moveEffects(ids, io);
3499 return NO_ERROR;
3500}
3501
Eric Laurentc75307b2015-03-17 15:29:32 -07003502bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3503{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003504 auto vs = toVolumeSource(stream, false);
3505 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003506}
3507
3508bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3509{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003510 auto vs = toVolumeSource(stream, false);
3511 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003512}
3513
Eric Laurente0720872014-03-11 09:30:41 -07003514bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003515{
3516 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003517 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003518 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003519 return true;
3520 }
3521 }
3522 return false;
3523}
3524
Eric Laurent275e8e92014-11-30 15:14:47 -08003525// Register a list of custom mixes with their attributes and format.
3526// When a mix is registered, corresponding input and output profiles are
3527// added to the remote submix hw module. The profile contains only the
3528// parameters (sampling rate, format...) specified by the mix.
3529// The corresponding input remote submix device is also connected.
3530//
3531// When a remote submix device is connected, the address is checked to select the
3532// appropriate profile and the corresponding input or output stream is opened.
3533//
3534// When capture starts, getInputForAttr() will:
3535// - 1 look for a mix matching the address passed in attribtutes tags if any
3536// - 2 if none found, getDeviceForInputSource() will:
3537// - 2.1 look for a mix matching the attributes source
3538// - 2.2 if none found, default to device selection by policy rules
3539// At this time, the corresponding output remote submix device is also connected
3540// and active playback use cases can be transferred to this mix if needed when reconnecting
3541// after AudioTracks are invalidated
3542//
3543// When playback starts, getOutputForAttr() will:
3544// - 1 look for a mix matching the address passed in attribtutes tags if any
3545// - 2 if none found, look for a mix matching the attributes usage
3546// - 3 if none found, default to device and output selection by policy rules.
3547
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003548status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003549{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003550 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3551 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003552 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003553 sp<HwModule> rSubmixModule;
3554 // examine each mix's route type
3555 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003556 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003557 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3558 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3559 ALOGE("Unsupported Policy Mix %zu of %zu: "
3560 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3561 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003562 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003563 break;
3564 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003565 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3566 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003567 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003568 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3569 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003570 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003571 rSubmixModule = mHwModules.getModuleFromName(
3572 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3573 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003574 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003575 i);
3576 res = INVALID_OPERATION;
3577 break;
3578 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003579 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003580
Eric Laurent97ac8712018-07-27 18:59:02 -07003581 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003582 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003583 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003584 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003585 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3586 } else {
3587 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3588 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003589 }
François Gaffie036e1e92015-03-19 10:16:24 +01003590
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003591 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003592 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003593 res = INVALID_OPERATION;
3594 break;
3595 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003596 audio_config_t outputConfig = mix.mFormat;
3597 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003598 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3599 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003600 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3601 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003602 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003603 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003604 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003605 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003606
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003607 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003608 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3609 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3610 ALOGE("Failed to set remote submix device available, type %u, address %s",
3611 mix.mDeviceType, address.string());
3612 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003613 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003614 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3615 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003616 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003617 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003618 i, mixes.size(), type, address.string());
3619
3620 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3621 mix.mDeviceType, mix.mDeviceAddress,
3622 String8(), AUDIO_FORMAT_DEFAULT);
3623 if (device == nullptr) {
3624 res = INVALID_OPERATION;
3625 break;
3626 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003627
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003628 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003629 // First try to find an already opened output supporting the device
3630 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003631 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003632
Eric Laurentc529cf62020-04-17 18:19:10 -07003633 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003634 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003635 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3636 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003637 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003638 } else {
3639 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003640 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003641 }
3642 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003643 // If no output found, try to find a direct output profile supporting the device
3644 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3645 sp<HwModule> module = mHwModules[i];
3646 for (size_t j = 0;
3647 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3648 j++) {
3649 sp<IOProfile> profile = module->getOutputProfiles()[j];
3650 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3651 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3652 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3653 address.string());
3654 res = INVALID_OPERATION;
3655 } else {
3656 foundOutput = true;
3657 }
3658 }
3659 }
3660 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003661 if (res != NO_ERROR) {
3662 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003663 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003664 res = INVALID_OPERATION;
3665 break;
3666 } else if (!foundOutput) {
3667 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003668 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003669 res = INVALID_OPERATION;
3670 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003671 } else {
3672 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003673 }
Eric Laurentc722f302014-12-10 11:21:49 -08003674 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003675 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003676 if (res != NO_ERROR) {
3677 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003678 } else if (checkOutputs) {
3679 checkForDeviceAndOutputChanges();
3680 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003681 }
3682 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003683}
3684
3685status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3686{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003687 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003688 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003689 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003690 sp<HwModule> rSubmixModule;
3691 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003692 for (const auto& mix : mixes) {
3693 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003694
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003695 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003696 rSubmixModule = mHwModules.getModuleFromName(
3697 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3698 if (rSubmixModule == 0) {
3699 res = INVALID_OPERATION;
3700 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003701 }
3702 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003703
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003704 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003705
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003706 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003707 res = INVALID_OPERATION;
3708 continue;
3709 }
3710
Kevin Rocard04ed0462019-05-02 17:53:24 -07003711 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3712 if (getDeviceConnectionState(device, address.string()) ==
3713 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3714 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3715 address.string(), "remote-submix",
3716 AUDIO_FORMAT_DEFAULT);
3717 if (res != OK) {
3718 ALOGE("Error making RemoteSubmix device unavailable for mix "
3719 "with type %d, address %s", device, address.string());
3720 }
3721 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003722 }
jiabin5740f082019-08-19 15:08:30 -07003723 rSubmixModule->removeOutputProfile(address.c_str());
3724 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003725
Kevin Rocard153f92d2018-12-18 18:33:28 -08003726 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003727 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003728 res = INVALID_OPERATION;
3729 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003730 } else {
3731 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003732 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003733 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003734 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003735 if (res == NO_ERROR && checkOutputs) {
3736 checkForDeviceAndOutputChanges();
3737 updateCallAndOutputRouting();
3738 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003739 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003740}
3741
Mikhail Naganov100f0122018-11-29 11:22:16 -08003742void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3743{
3744 size_t i = 0;
3745 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3746 for (const auto& fmt : mManualSurroundFormats) {
3747 if (i++ != 0) dst->append(", ");
3748 std::string sfmt;
3749 FormatConverter::toString(fmt, sfmt);
3750 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3751 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3752 }
3753}
3754
Eric Laurentc529cf62020-04-17 18:19:10 -07003755// Returns true if all devices types match the predicate and are supported by one HW module
3756bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003757 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003758 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003759 const char *context,
3760 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003761 for (size_t i = 0; i < devices.size(); i++) {
3762 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003763 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003764 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003765 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003766 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003767 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003768 return false;
3769 }
3770 }
3771 return true;
3772}
3773
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003774status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003775 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003776 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003777 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3778 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003779 }
3780 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003781 if (res != NO_ERROR) {
3782 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3783 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003784 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003785
3786 checkForDeviceAndOutputChanges();
3787 updateCallAndOutputRouting();
3788
3789 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003790}
3791
3792status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3793 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003794 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3795 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003796 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003797 __FUNCTION__, uid);
3798 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003799 }
3800
Eric Laurentc529cf62020-04-17 18:19:10 -07003801 checkForDeviceAndOutputChanges();
3802 updateCallAndOutputRouting();
3803
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003804 return res;
3805}
3806
Eric Laurent2517af32020-11-25 15:31:27 +01003807
jiabin0a488932020-08-07 17:32:40 -07003808status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3809 device_role_t role,
3810 const AudioDeviceTypeAddrVector &devices) {
3811 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3812 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003813
Eric Laurentc529cf62020-04-17 18:19:10 -07003814 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003815 return BAD_VALUE;
3816 }
jiabin0a488932020-08-07 17:32:40 -07003817 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003818 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003819 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3820 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003821 return status;
3822 }
3823
3824 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003825
3826 bool forceVolumeReeval = false;
3827 // FIXME: workaround for truncated touch sounds
3828 // to be removed when the problem is handled by system UI
3829 uint32_t delayMs = 0;
3830 if (strategy == mCommunnicationStrategy) {
3831 forceVolumeReeval = true;
3832 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3833 updateInputRouting();
3834 }
3835 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003836
3837 return NO_ERROR;
3838}
3839
3840void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3841{
3842 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003843 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003844 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003845 // Only apply special touch sound delay once
3846 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003847 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003848 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003849 for (size_t i = 0; i < mOutputs.size(); i++) {
3850 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3851 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003852 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3853 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003854 // As done in setDeviceConnectionState, we could also fix default device issue by
3855 // preventing the force re-routing in case of default dev that distinguishes on address.
3856 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003857 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003858 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3859 // If the device is using preferred mixer attributes, the output need to reopen
3860 // with default configuration when the new selected devices are different from
3861 // current routing devices.
3862 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3863 continue;
3864 }
Francois Gaffie601801d2021-06-22 13:27:39 +02003865 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3866 true /*requiresMuteCheck*/,
3867 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003868 // Only apply special touch sound delay once
3869 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003870 }
3871 if (forceVolumeReeval && !newDevices.isEmpty()) {
3872 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3873 }
3874 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003875 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01003876 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003877}
3878
Eric Laurent2517af32020-11-25 15:31:27 +01003879void AudioPolicyManager::updateInputRouting() {
3880 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303881 // Skip for hotword recording as the input device switch
3882 // is handled within sound trigger HAL
3883 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3884 continue;
3885 }
Eric Laurent2517af32020-11-25 15:31:27 +01003886 auto newDevice = getNewInputDevice(activeDesc);
3887 // Force new input selection if the new device can not be reached via current input
3888 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3889 setInputDevice(activeDesc->mIoHandle, newDevice);
3890 } else {
3891 closeInput(activeDesc->mIoHandle);
3892 }
3893 }
3894}
3895
Paul Wang5d7cdb52022-11-22 09:45:06 +00003896status_t
3897AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3898 device_role_t role,
3899 const AudioDeviceTypeAddrVector &devices) {
3900 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3901 dumpAudioDeviceTypeAddrVector(devices).c_str());
3902
Eric Laurent78fedbf2023-03-09 14:40:44 +01003903 if (!areAllDevicesSupported(
3904 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00003905 return BAD_VALUE;
3906 }
3907 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
3908 if (status != NO_ERROR) {
3909 ALOGW("Engine could not remove devices %s for strategy %d role %d",
3910 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
3911 return status;
3912 }
3913
3914 checkForDeviceAndOutputChanges();
3915
3916 bool forceVolumeReeval = false;
3917 // TODO(b/263479999): workaround for truncated touch sounds
3918 // to be removed when the problem is handled by system UI
3919 uint32_t delayMs = 0;
3920 if (strategy == mCommunnicationStrategy) {
3921 forceVolumeReeval = true;
3922 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3923 updateInputRouting();
3924 }
3925 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
3926
3927 return NO_ERROR;
3928}
3929
3930status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
3931 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003932{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003933 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003934
Paul Wang5d7cdb52022-11-22 09:45:06 +00003935 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003936 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01003937 ALOGW_IF(status != NAME_NOT_FOUND,
3938 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01003939 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003940 return status;
3941 }
3942
3943 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003944
3945 bool forceVolumeReeval = false;
3946 // FIXME: workaround for truncated touch sounds
3947 // to be removed when the problem is handled by system UI
3948 uint32_t delayMs = 0;
3949 if (strategy == mCommunnicationStrategy) {
3950 forceVolumeReeval = true;
3951 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3952 updateInputRouting();
3953 }
3954 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003955
3956 return NO_ERROR;
3957}
3958
jiabin0a488932020-08-07 17:32:40 -07003959status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3960 device_role_t role,
3961 AudioDeviceTypeAddrVector &devices) {
3962 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003963}
3964
Jiabin Huang3b98d322020-09-03 17:54:16 +00003965status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3966 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3967 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3968 dumpAudioDeviceTypeAddrVector(devices).c_str());
3969
Mikhail Naganov55773032020-10-01 15:08:13 -07003970 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003971 return BAD_VALUE;
3972 }
3973 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3974 ALOGW_IF(status != NO_ERROR,
3975 "Engine could not set preferred devices %s for audio source %d role %d",
3976 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3977
3978 return status;
3979}
3980
3981status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3982 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3983 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3984 dumpAudioDeviceTypeAddrVector(devices).c_str());
3985
Mikhail Naganov55773032020-10-01 15:08:13 -07003986 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003987 return BAD_VALUE;
3988 }
3989 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3990 ALOGW_IF(status != NO_ERROR,
3991 "Engine could not add preferred devices %s for audio source %d role %d",
3992 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3993
Eric Laurent2517af32020-11-25 15:31:27 +01003994 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003995 return status;
3996}
3997
3998status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3999 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4000{
4001 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4002 dumpAudioDeviceTypeAddrVector(devices).c_str());
4003
Eric Laurent78fedbf2023-03-09 14:40:44 +01004004 if (!areAllDevicesSupported(
4005 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004006 return BAD_VALUE;
4007 }
4008
4009 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4010 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004011 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004012 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004013 if (status == NO_ERROR) {
4014 updateInputRouting();
4015 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004016 return status;
4017}
4018
4019status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4020 device_role_t role) {
4021 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4022
4023 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004024 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004025 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004026 if (status == NO_ERROR) {
4027 updateInputRouting();
4028 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004029 return status;
4030}
4031
4032status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4033 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4034 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4035}
4036
Oscar Azucena90e77632019-11-27 17:12:28 -08004037status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004038 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004039 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004040 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4041 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004042 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004043 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4044 if (status != NO_ERROR) {
4045 ALOGE("%s() could not set device affinity for userId %d",
4046 __FUNCTION__, userId);
4047 return status;
4048 }
4049
4050 // reevaluate outputs for all devices
4051 checkForDeviceAndOutputChanges();
4052 updateCallAndOutputRouting();
4053
4054 return NO_ERROR;
4055}
4056
4057status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004058 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08004059 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4060 if (status != NO_ERROR) {
4061 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4062 __FUNCTION__, userId);
4063 return status;
4064 }
4065
4066 // reevaluate outputs for all devices
4067 checkForDeviceAndOutputChanges();
4068 updateCallAndOutputRouting();
4069
4070 return NO_ERROR;
4071}
4072
Andy Hungc29d82b2018-10-05 12:23:17 -07004073void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004074{
Andy Hungc29d82b2018-10-05 12:23:17 -07004075 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004076 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004077 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004078 std::string stateLiteral;
4079 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004080 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004081 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4082 "communications", "media", "record", "dock", "system",
4083 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4084 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4085 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004086 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4087 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4088 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4089 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4090 dst->append(" (MANUAL: ");
4091 dumpManualSurroundFormats(dst);
4092 dst->append(")");
4093 }
4094 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004095 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004096 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4097 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004098 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07004099 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01004100
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004101 dst->append("\n");
4102 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4103 dst->append("\n");
4104 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004105 mHwModulesAll.dump(dst);
4106 mOutputs.dump(dst);
4107 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004108 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004109 mAudioPatches.dump(dst);
4110 mPolicyMixes.dump(dst);
4111 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004112
Kevin Rocardb99cc752019-03-21 20:52:24 -07004113 dst->appendFormat(" AllowedCapturePolicies:\n");
4114 for (auto& policy : mAllowedCapturePolicies) {
4115 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4116 }
4117
jiabina84c3d32022-12-02 18:59:55 +00004118 dst->appendFormat(" Preferred mixer audio configuration:\n");
4119 for (const auto it : mPreferredMixerAttrInfos) {
4120 dst->appendFormat(" - device port id: %d\n", it.first);
4121 for (const auto preferredMixerInfoIt : it.second) {
4122 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4123 preferredMixerInfoIt.second->dump(dst);
4124 }
4125 }
4126
François Gaffiec005e562018-11-06 15:04:49 +01004127 dst->appendFormat("\nPolicy Engine dump:\n");
4128 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004129}
4130
4131status_t AudioPolicyManager::dump(int fd)
4132{
4133 String8 result;
4134 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07004135 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004136 return NO_ERROR;
4137}
4138
Kevin Rocardb99cc752019-03-21 20:52:24 -07004139status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4140{
4141 mAllowedCapturePolicies[uid] = capturePolicy;
4142 return NO_ERROR;
4143}
4144
Eric Laurente552edb2014-03-10 17:42:56 -07004145// This function checks for the parameters which can be offloaded.
4146// This can be enhanced depending on the capability of the DSP and policy
4147// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004148audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004149{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004150 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004151 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004152 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004153 offloadInfo.format,
4154 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4155 offloadInfo.has_video);
4156
jiabin2b9d5a12021-12-10 01:06:29 +00004157 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004158 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004159 }
4160
4161 // See if there is a profile to support this.
4162 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004163 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004164 offloadInfo.sample_rate,
4165 offloadInfo.format,
4166 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004167 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4168 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004169 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4170 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4171 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004172 if (profile == nullptr) {
4173 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4174 }
4175 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4176 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4177 }
4178 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004179}
4180
Michael Chana94fbb22018-04-24 14:31:19 +10004181bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4182 const audio_attributes_t& attributes) {
4183 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004184 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004185 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4186 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004187 config.sample_rate,
4188 config.format,
4189 config.channel_mask,
4190 output_flags,
4191 true /* directOnly */);
4192 ALOGV("%s() profile %sfound with name: %s, "
4193 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4194 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004195 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004196 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004197
4198 // also try the MSD module if compatible profile not found
4199 if (profile == nullptr) {
4200 profile = getMsdProfileForOutput(outputDevices,
4201 config.sample_rate,
4202 config.format,
4203 config.channel_mask,
4204 output_flags,
4205 true /* directOnly */);
4206 ALOGV("%s() MSD profile %sfound with name: %s, "
4207 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4208 __FUNCTION__, profile != 0 ? "" : "NOT ",
4209 (profile != 0 ? profile->getTagName().c_str() : "null"),
4210 config.sample_rate, config.format, config.channel_mask, output_flags);
4211 }
4212 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004213}
4214
jiabin2b9d5a12021-12-10 01:06:29 +00004215bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4216 bool durationIgnored) {
4217 if (mMasterMono) {
4218 return false; // no offloading if mono is set.
4219 }
4220
4221 // Check if offload has been disabled
4222 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4223 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4224 return false;
4225 }
4226
4227 // Check if stream type is music, then only allow offload as of now.
4228 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4229 {
4230 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4231 return false;
4232 }
4233
4234 //TODO: enable audio offloading with video when ready
4235 const bool allowOffloadWithVideo =
4236 property_get_bool("audio.offload.video", false /* default_value */);
4237 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4238 ALOGV("%s: has_video == true, returning false", __func__);
4239 return false;
4240 }
4241
4242 //If duration is less than minimum value defined in property, return false
4243 const int min_duration_secs = property_get_int32(
4244 "audio.offload.min.duration.secs", -1 /* default_value */);
4245 if (!durationIgnored) {
4246 if (min_duration_secs >= 0) {
4247 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4248 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4249 __func__, min_duration_secs);
4250 return false;
4251 }
4252 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4253 ALOGV("%s: Offload denied by duration < default min(=%u)",
4254 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4255 return false;
4256 }
4257 }
4258
4259 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4260 // creating an offloaded track and tearing it down immediately after start when audioflinger
4261 // detects there is an active non offloadable effect.
4262 // FIXME: We should check the audio session here but we do not have it in this context.
4263 // This may prevent offloading in rare situations where effects are left active by apps
4264 // in the background.
4265 if (mEffects.isNonOffloadableEffectEnabled()) {
4266 return false;
4267 }
4268
4269 return true;
4270}
4271
4272audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4273 const audio_config_t *config) {
4274 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4275 offloadInfo.format = config->format;
4276 offloadInfo.sample_rate = config->sample_rate;
4277 offloadInfo.channel_mask = config->channel_mask;
4278 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4279 offloadInfo.has_video = false;
4280 offloadInfo.is_streaming = false;
4281 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4282
4283 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4284 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4285 audio_flags_to_audio_output_flags(attr->flags, &flags);
4286 // only retain flags that will drive compressed offload or passthrough
4287 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4288 if (offloadPossible) {
4289 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4290 }
4291 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4292
Dorin Drimusfae3c642022-03-17 18:36:30 +01004293 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004294 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004295 DeviceVector outputDevices = engineOutputDevices;
4296 // the MSD module checks for different conditions and output devices
4297 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4298 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4299 continue;
4300 }
4301 outputDevices = getMsdAudioOutDevices();
4302 }
jiabin2b9d5a12021-12-10 01:06:29 +00004303 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004304 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004305 config->sample_rate, nullptr /*updatedSamplingRate*/,
4306 config->format, nullptr /*updatedFormat*/,
4307 config->channel_mask, nullptr /*updatedChannelMask*/,
4308 flags)) {
4309 continue;
4310 }
4311 // reject profiles not corresponding to a device currently available
4312 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4313 continue;
4314 }
4315 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4316 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004317 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004318 != AUDIO_DIRECT_NOT_SUPPORTED) {
4319 // Already reports offload gapless supported. No need to report offload support.
4320 continue;
4321 }
4322 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4323 != AUDIO_OUTPUT_FLAG_NONE) {
4324 // If offload gapless is reported, no need to report offload support.
4325 directMode = (audio_direct_mode_t) ((directMode &
4326 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4327 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4328 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004329 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004330 }
4331 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004332 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004333 }
4334 }
4335 }
4336 return directMode;
4337}
4338
Dorin Drimusf2196d82022-01-03 12:11:18 +01004339status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4340 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004341 if (mEffects.isNonOffloadableEffectEnabled()) {
4342 return OK;
4343 }
jiabinf1c73972022-04-14 16:28:52 -07004344 DeviceVector devices;
4345 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004346 if (status != OK) {
4347 return status;
4348 }
4349 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4350 if (devices.empty()) {
4351 return OK; // no output devices for the attributes
4352 }
jiabinf1c73972022-04-14 16:28:52 -07004353 return getProfilesForDevices(devices, audioProfilesVector,
4354 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004355}
4356
jiabina84c3d32022-12-02 18:59:55 +00004357status_t AudioPolicyManager::getSupportedMixerAttributes(
4358 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4359 ALOGV("%s, portId=%d", __func__, portId);
4360 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4361 if (deviceDescriptor == nullptr) {
4362 ALOGE("%s the requested device is currently unavailable", __func__);
4363 return BAD_VALUE;
4364 }
4365 for (const auto& hwModule : mHwModules) {
4366 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4367 if (curProfile->supportsDevice(deviceDescriptor)) {
4368 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4369 }
4370 }
4371 }
4372 return NO_ERROR;
4373}
4374
4375status_t AudioPolicyManager::setPreferredMixerAttributes(
4376 const audio_attributes_t *attr,
4377 audio_port_handle_t portId,
4378 uid_t uid,
4379 const audio_mixer_attributes_t *mixerAttributes) {
4380 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4381 "mixerBehavior=%d}, uid=%d, portId=%u",
4382 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4383 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4384 mixerAttributes->mixer_behavior, uid, portId);
4385 if (attr->usage != AUDIO_USAGE_MEDIA) {
4386 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4387 return BAD_VALUE;
4388 }
4389 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4390 if (deviceDescriptor == nullptr) {
4391 ALOGE("%s the requested device is currently unavailable", __func__);
4392 return BAD_VALUE;
4393 }
4394 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4395 ALOGE("%s(%d), type=%d, is not a usb output device",
4396 __func__, portId, deviceDescriptor->type());
4397 return BAD_VALUE;
4398 }
4399
4400 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4401 audio_flags_to_audio_output_flags(attr->flags, &flags);
4402 flags = (audio_output_flags_t) (flags |
4403 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4404 sp<IOProfile> profile = nullptr;
4405 DeviceVector devices(deviceDescriptor);
4406 for (const auto& hwModule : mHwModules) {
4407 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4408 if (curProfile->hasDynamicAudioProfile()
4409 && curProfile->isCompatibleProfile(devices,
4410 mixerAttributes->config.sample_rate,
4411 nullptr /*updatedSamplingRate*/,
4412 mixerAttributes->config.format,
4413 nullptr /*updatedFormat*/,
4414 mixerAttributes->config.channel_mask,
4415 nullptr /*updatedChannelMask*/,
4416 flags,
4417 false /*exactMatchRequiredForInputFlags*/)) {
4418 profile = curProfile;
4419 break;
4420 }
4421 }
4422 }
4423 if (profile == nullptr) {
4424 ALOGE("%s, there is no compatible profile found", __func__);
4425 return BAD_VALUE;
4426 }
4427
4428 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4429 sp<PreferredMixerAttributesInfo>::make(
4430 uid, portId, profile, flags, *mixerAttributes);
4431 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4432 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4433
4434 // If 1) there is any client from the preferred mixer configuration owner that is currently
4435 // active and matches the strategy and 2) current output is on the preferred device and the
4436 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4437 // configuration.
4438 std::vector<audio_io_handle_t> outputsToReopen;
4439 for (size_t i = 0; i < mOutputs.size(); i++) {
4440 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004441 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4442 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4443 output->mUsePreferredMixerAttributes = true;
4444 } else {
4445 for (const auto &client: output->getActiveClients()) {
4446 if (client->uid() == uid && client->strategy() == strategy) {
4447 client->setIsInvalid();
4448 outputsToReopen.push_back(output->mIoHandle);
4449 }
jiabina84c3d32022-12-02 18:59:55 +00004450 }
4451 }
4452 }
4453 }
4454 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4455 config.sample_rate = mixerAttributes->config.sample_rate;
4456 config.channel_mask = mixerAttributes->config.channel_mask;
4457 config.format = mixerAttributes->config.format;
4458 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004459 sp<SwAudioOutputDescriptor> desc =
4460 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4461 if (desc == nullptr) {
4462 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4463 continue;
4464 }
4465 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004466 }
4467
4468 return NO_ERROR;
4469}
4470
4471sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
4472 audio_port_handle_t devicePortId, product_strategy_t strategy) {
4473 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4474 if (it == mPreferredMixerAttrInfos.end()) {
4475 return nullptr;
4476 }
4477 auto mixerAttrInfoIt = it->second.find(strategy);
4478 if (mixerAttrInfoIt == it->second.end()) {
4479 return nullptr;
4480 }
4481 return mixerAttrInfoIt->second;
4482}
4483
4484status_t AudioPolicyManager::getPreferredMixerAttributes(
4485 const audio_attributes_t *attr,
4486 audio_port_handle_t portId,
4487 audio_mixer_attributes_t* mixerAttributes) {
4488 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4489 portId, mEngine->getProductStrategyForAttributes(*attr));
4490 if (info == nullptr) {
4491 return NAME_NOT_FOUND;
4492 }
4493 *mixerAttributes = info->getMixerAttributes();
4494 return NO_ERROR;
4495}
4496
4497status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4498 audio_port_handle_t portId,
4499 uid_t uid) {
4500 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4501 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4502 if (preferredMixerAttrInfo == nullptr) {
4503 return NAME_NOT_FOUND;
4504 }
4505 if (preferredMixerAttrInfo->getUid() != uid) {
4506 ALOGE("%s, requested uid=%d, owned uid=%d",
4507 __func__, uid, preferredMixerAttrInfo->getUid());
4508 return PERMISSION_DENIED;
4509 }
4510 mPreferredMixerAttrInfos[portId].erase(strategy);
4511 if (mPreferredMixerAttrInfos[portId].empty()) {
4512 mPreferredMixerAttrInfos.erase(portId);
4513 }
4514
4515 // Reconfig existing output
4516 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4517 for (size_t i = 0; i < mOutputs.size(); i++) {
4518 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4519 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4520 }
4521 }
4522 for (const auto output : potentialOutputsToReopen) {
4523 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4524 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4525 preferredMixerAttrInfo->getFlags())) {
4526 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4527 }
4528 }
4529 return NO_ERROR;
4530}
4531
Eric Laurent6a94d692014-05-20 11:18:06 -07004532status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4533 audio_port_type_t type,
4534 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004535 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004536 unsigned int *generation)
4537{
jiabin19cdba52020-11-24 11:28:58 -08004538 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4539 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004540 return BAD_VALUE;
4541 }
4542 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004543 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004544 *num_ports = 0;
4545 }
4546
4547 size_t portsWritten = 0;
4548 size_t portsMax = *num_ports;
4549 *num_ports = 0;
4550 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004551 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4552 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004553 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004554 for (const auto& dev : mAvailableOutputDevices) {
4555 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004556 continue;
4557 }
4558 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004559 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004560 }
4561 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004562 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004563 }
4564 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004565 for (const auto& dev : mAvailableInputDevices) {
4566 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004567 continue;
4568 }
4569 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004570 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004571 }
4572 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004573 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004574 }
4575 }
4576 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4577 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4578 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4579 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4580 }
4581 *num_ports += mInputs.size();
4582 }
4583 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004584 size_t numOutputs = 0;
4585 for (size_t i = 0; i < mOutputs.size(); i++) {
4586 if (!mOutputs[i]->isDuplicated()) {
4587 numOutputs++;
4588 if (portsWritten < portsMax) {
4589 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4590 }
4591 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004592 }
Eric Laurent84c70242014-06-23 08:46:27 -07004593 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004594 }
4595 }
jiabina84c3d32022-12-02 18:59:55 +00004596
Eric Laurent6a94d692014-05-20 11:18:06 -07004597 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004598 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004599 return NO_ERROR;
4600}
4601
jiabin19cdba52020-11-24 11:28:58 -08004602status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004603{
Eric Laurent99fcae42018-05-17 16:59:18 -07004604 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4605 return BAD_VALUE;
4606 }
4607 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4608 if (dev != 0) {
4609 dev->toAudioPort(port);
4610 return NO_ERROR;
4611 }
4612 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4613 if (dev != 0) {
4614 dev->toAudioPort(port);
4615 return NO_ERROR;
4616 }
4617 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4618 if (out != 0) {
4619 out->toAudioPort(port);
4620 return NO_ERROR;
4621 }
4622 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4623 if (in != 0) {
4624 in->toAudioPort(port);
4625 return NO_ERROR;
4626 }
4627 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004628}
4629
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004630status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4631 audio_patch_handle_t *handle,
4632 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004633{
François Gaffieafd4cea2019-11-18 15:50:22 +01004634 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004635 if (handle == NULL || patch == NULL) {
4636 return BAD_VALUE;
4637 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004638 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004639 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004640 return BAD_VALUE;
4641 }
4642 // only one source per audio patch supported for now
4643 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004644 return INVALID_OPERATION;
4645 }
Eric Laurent874c42872014-08-08 15:13:39 -07004646 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004647 return INVALID_OPERATION;
4648 }
Eric Laurent874c42872014-08-08 15:13:39 -07004649 for (size_t i = 0; i < patch->num_sinks; i++) {
4650 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4651 return INVALID_OPERATION;
4652 }
4653 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004654
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004655 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4656 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4657 if (srcDevice == nullptr || sinkDevice == nullptr) {
4658 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4659 return BAD_VALUE;
4660 }
4661 ALOGV("%s between source %s and sink %s", __func__,
4662 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4663 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4664 // Default attributes, default volume priority, not to infer with non raw audio patches.
4665 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4666 const struct audio_port_config *source = &patch->sources[0];
4667 sp<SourceClientDescriptor> sourceDesc =
4668 new InternalSourceClientDescriptor(
4669 portId, uid, attributes, *source, srcDevice, sinkDevice,
4670 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4671
4672 status_t status =
4673 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4674
4675 if (status != NO_ERROR) {
4676 return INVALID_OPERATION;
4677 }
4678 mAudioSources.add(portId, sourceDesc);
4679 return NO_ERROR;
4680}
4681
4682status_t AudioPolicyManager::connectAudioSourceToSink(
4683 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4684 const struct audio_patch *patch,
4685 audio_patch_handle_t &handle,
4686 uid_t uid, uint32_t delayMs)
4687{
4688 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4689 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4690 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4691 return INVALID_OPERATION;
4692 }
4693 sourceDesc->connect(handle, sinkDevice);
4694 if (isMsdPatch(handle)) {
4695 return NO_ERROR;
4696 }
4697 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4698 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4699 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4700 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4701 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4702 goto FailurePatchAdded;
4703 }
4704 status = swOutput->start();
4705 if (status != NO_ERROR) {
4706 goto FailureSourceAdded;
4707 }
4708 swOutput->addClient(sourceDesc);
4709 status = startSource(swOutput, sourceDesc, &delayMs);
4710 if (status != NO_ERROR) {
4711 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4712 goto FailureSourceActive;
4713 }
4714 if (delayMs != 0) {
4715 usleep(delayMs * 1000);
4716 }
4717 return NO_ERROR;
4718
4719FailureSourceActive:
4720 swOutput->stop();
4721 releaseOutput(sourceDesc->portId());
4722FailureSourceAdded:
4723 sourceDesc->setSwOutput(nullptr);
4724FailurePatchAdded:
4725 releaseAudioPatchInternal(handle);
4726 return INVALID_OPERATION;
4727}
4728
4729status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4730 audio_patch_handle_t *handle,
4731 uid_t uid, uint32_t delayMs,
4732 const sp<SourceClientDescriptor>& sourceDesc)
4733{
4734 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004735 sp<AudioPatch> patchDesc;
4736 ssize_t index = mAudioPatches.indexOfKey(*handle);
4737
François Gaffieafd4cea2019-11-18 15:50:22 +01004738 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4739 patch->sources[0].role,
4740 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004741#if LOG_NDEBUG == 0
4742 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004743 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4744 patch->sinks[i].role,
4745 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004746 }
4747#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004748
4749 if (index >= 0) {
4750 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004751 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4752 __func__, mUidCached, patchDesc->getUid(), uid);
4753 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004754 return INVALID_OPERATION;
4755 }
4756 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004757 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004758 }
4759
4760 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004761 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004762 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004763 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004764 return BAD_VALUE;
4765 }
Eric Laurent84c70242014-06-23 08:46:27 -07004766 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4767 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004768 if (patchDesc != 0) {
4769 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004770 ALOGV("%s source id differs for patch current id %d new id %d",
4771 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004772 return BAD_VALUE;
4773 }
4774 }
Eric Laurent874c42872014-08-08 15:13:39 -07004775 DeviceVector devices;
4776 for (size_t i = 0; i < patch->num_sinks; i++) {
4777 // Only support mix to devices connection
4778 // TODO add support for mix to mix connection
4779 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004780 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004781 return INVALID_OPERATION;
4782 }
4783 sp<DeviceDescriptor> devDesc =
4784 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4785 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004786 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004787 return BAD_VALUE;
4788 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004789
François Gaffie11d30102018-11-02 16:09:09 +01004790 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004791 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004792 NULL, // updatedSamplingRate
4793 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004794 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004795 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004796 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004797 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004798 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004799 return INVALID_OPERATION;
4800 }
4801 devices.add(devDesc);
4802 }
4803 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004804 return INVALID_OPERATION;
4805 }
Eric Laurent874c42872014-08-08 15:13:39 -07004806
Eric Laurent6a94d692014-05-20 11:18:06 -07004807 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004808 ALOGV("%s setting device %s on output %d",
4809 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004810 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004811 index = mAudioPatches.indexOfKey(*handle);
4812 if (index >= 0) {
4813 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004814 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004815 }
4816 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004817 patchDesc->setUid(uid);
4818 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004819 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004820 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004821 return INVALID_OPERATION;
4822 }
4823 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4824 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4825 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004826 // only one sink supported when connecting an input device to a mix
4827 if (patch->num_sinks > 1) {
4828 return INVALID_OPERATION;
4829 }
François Gaffie53615e22015-03-19 09:24:12 +01004830 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004831 if (inputDesc == NULL) {
4832 return BAD_VALUE;
4833 }
4834 if (patchDesc != 0) {
4835 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4836 return BAD_VALUE;
4837 }
4838 }
François Gaffie11d30102018-11-02 16:09:09 +01004839 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004840 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004841 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004842 return BAD_VALUE;
4843 }
4844
François Gaffie11d30102018-11-02 16:09:09 +01004845 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004846 patch->sinks[0].sample_rate,
4847 NULL, /*updatedSampleRate*/
4848 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004849 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004850 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004851 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004852 // FIXME for the parameter type,
4853 // and the NONE
4854 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004855 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004856 return INVALID_OPERATION;
4857 }
4858 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004859 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004860 device->toString().c_str(), inputDesc->mIoHandle);
4861 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004862 index = mAudioPatches.indexOfKey(*handle);
4863 if (index >= 0) {
4864 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004865 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004866 }
4867 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004868 patchDesc->setUid(uid);
4869 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004870 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004871 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004872 return INVALID_OPERATION;
4873 }
4874 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4875 // device to device connection
4876 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004877 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004878 return BAD_VALUE;
4879 }
4880 }
François Gaffie11d30102018-11-02 16:09:09 +01004881 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004882 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004883 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004884 return BAD_VALUE;
4885 }
Eric Laurent874c42872014-08-08 15:13:39 -07004886
Eric Laurent6a94d692014-05-20 11:18:06 -07004887 //update source and sink with our own data as the data passed in the patch may
4888 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004889 PatchBuilder patchBuilder;
4890 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004891
4892 // if first sink is to MSD, establish single MSD patch
4893 if (getMsdAudioOutDevices().contains(
4894 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4895 ALOGV("%s patching to MSD", __FUNCTION__);
4896 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4897 goto installPatch;
4898 }
4899
François Gaffieafd4cea2019-11-18 15:50:22 +01004900 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4901 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004902
Eric Laurent874c42872014-08-08 15:13:39 -07004903 for (size_t i = 0; i < patch->num_sinks; i++) {
4904 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004905 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004906 return INVALID_OPERATION;
4907 }
François Gaffie11d30102018-11-02 16:09:09 +01004908 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004909 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004910 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004911 return BAD_VALUE;
4912 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004913 audio_port_config sinkPortConfig = {};
4914 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4915 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004916
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004917 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4918 // volume management purpose (tracking activity)
4919 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4920 // in config XML to reach the sink so that is can be declared as available.
4921 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004922 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004923 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004924 // take care of dynamic routing for SwOutput selection,
4925 audio_attributes_t attributes = sourceDesc->attributes();
4926 audio_stream_type_t stream = sourceDesc->stream();
4927 audio_attributes_t resultAttr;
4928 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4929 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02004930 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
4931 config.channel_mask =
4932 (audio_channel_mask_get_representation(sourceMask)
4933 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
4934 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004935 config.format = sourceDesc->config().format;
4936 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4937 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4938 bool isRequestedDeviceForExclusiveUse = false;
4939 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004940 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00004941 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004942 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4943 &stream, sourceDesc->uid(), &config, &flags,
4944 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00004945 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004946 if (output == AUDIO_IO_HANDLE_NONE) {
4947 ALOGV("%s no output for device %s",
4948 __FUNCTION__, sinkDevice->toString().c_str());
4949 return INVALID_OPERATION;
4950 }
4951 outputDesc = mOutputs.valueFor(output);
4952 if (outputDesc->isDuplicated()) {
4953 ALOGE("%s output is duplicated", __func__);
4954 return INVALID_OPERATION;
4955 }
François Gaffie7e39df22022-04-26 12:48:49 +02004956 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4957 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004958 } else {
4959 // Same for "raw patches" aka created from createAudioPatch API
4960 SortedVector<audio_io_handle_t> outputs =
4961 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4962 // if the sink device is reachable via an opened output stream, request to
4963 // go via this output stream by adding a second source to the patch
4964 // description
4965 output = selectOutput(outputs);
4966 if (output == AUDIO_IO_HANDLE_NONE) {
4967 ALOGE("%s no output available for internal patch sink", __func__);
4968 return INVALID_OPERATION;
4969 }
4970 outputDesc = mOutputs.valueFor(output);
4971 if (outputDesc->isDuplicated()) {
4972 ALOGV("%s output for device %s is duplicated",
4973 __func__, sinkDevice->toString().c_str());
4974 return INVALID_OPERATION;
4975 }
François Gaffie7e39df22022-04-26 12:48:49 +02004976 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004977 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004978 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004979 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004980 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004981 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004982 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4983 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004984 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4985 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004986 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004987 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004988 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004989 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004990 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004991 return INVALID_OPERATION;
4992 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004993 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004994 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004995 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004996 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004997 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02004998 srcMixPortConfig.ext.mix.usecase.stream =
4999 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005000 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5001 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005002 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005003 }
Eric Laurent83b88082014-06-20 18:31:16 -07005004 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005005 }
5006 // TODO: check from routing capabilities in config file and other conflicting patches
5007
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005008installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005009 status_t status = installPatch(
5010 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005011 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005012 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005013 return INVALID_OPERATION;
5014 }
5015 } else {
5016 return BAD_VALUE;
5017 }
5018 } else {
5019 return BAD_VALUE;
5020 }
5021 return NO_ERROR;
5022}
5023
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005024status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005025{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005026 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005027 ssize_t index = mAudioPatches.indexOfKey(handle);
5028
5029 if (index < 0) {
5030 return BAD_VALUE;
5031 }
5032 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005033 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5034 __func__, mUidCached, patchDesc->getUid(), uid);
5035 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005036 return INVALID_OPERATION;
5037 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005038 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5039 for (size_t i = 0; i < mAudioSources.size(); i++) {
5040 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5041 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5042 portId = sourceDesc->portId();
5043 break;
5044 }
5045 }
5046 return portId != AUDIO_PORT_HANDLE_NONE ?
5047 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005048}
Eric Laurent6a94d692014-05-20 11:18:06 -07005049
François Gaffieafd4cea2019-11-18 15:50:22 +01005050status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005051 uint32_t delayMs,
5052 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005053{
5054 ALOGV("%s patch %d", __func__, handle);
5055 if (mAudioPatches.indexOfKey(handle) < 0) {
5056 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5057 return BAD_VALUE;
5058 }
5059 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005060 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005061 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005062 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005063 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005064 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005065 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005066 return BAD_VALUE;
5067 }
5068
François Gaffie11d30102018-11-02 16:09:09 +01005069 setOutputDevices(outputDesc,
5070 getNewOutputDevices(outputDesc, true /*fromCache*/),
5071 true,
5072 0,
5073 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005074 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5075 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005076 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005077 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005078 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005079 return BAD_VALUE;
5080 }
5081 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005082 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005083 true,
5084 NULL);
5085 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005086 status_t status =
5087 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5088 ALOGV("%s patch panel returned %d patchHandle %d",
5089 __func__, status, patchDesc->getAfHandle());
5090 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005091 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005092 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005093 // SW or HW Bridge
5094 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5095 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005096 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005097 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5098 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5099 outputDesc = sourceDesc->swOutput().promote();
5100 }
5101 if (outputDesc == nullptr) {
5102 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5103 // releaseOutput has already called closeOutput in case of direct output
5104 return NO_ERROR;
5105 }
François Gaffie7e39df22022-04-26 12:48:49 +02005106 patchHandle = outputDesc->getPatchHandle();
5107 // When a Sw bridge is released, the mixer used by this bridge will release its
5108 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
5109 // Reuse patch handle to force audio flinger removing initial mixer patch removal
5110 // updating hal patch handle (prevent leaks).
5111 // While using a HwBridge, force reconsidering device only if not reusing an existing
5112 // output and no more activity on output (will force to close).
5113 bool force = sourceDesc->useSwBridge() ||
5114 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
5115 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5116 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5117 // Reconsider device only for cases:
5118 // 1 / Active Output
5119 // 2 / Inactive Output previously hosting HwBridge
5120 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5121 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5122 sourceDesc->canCloseOutput();
5123 setOutputDevices(outputDesc,
5124 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5125 outputDesc->devices(),
5126 force,
5127 0,
5128 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005129 } else {
5130 return BAD_VALUE;
5131 }
5132 } else {
5133 return BAD_VALUE;
5134 }
5135 return NO_ERROR;
5136}
5137
5138status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5139 struct audio_patch *patches,
5140 unsigned int *generation)
5141{
François Gaffie53615e22015-03-19 09:24:12 +01005142 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005143 return BAD_VALUE;
5144 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005145 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005146 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005147}
5148
Eric Laurente1715a42014-05-20 11:30:42 -07005149status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005150{
Eric Laurente1715a42014-05-20 11:30:42 -07005151 ALOGV("setAudioPortConfig()");
5152
5153 if (config == NULL) {
5154 return BAD_VALUE;
5155 }
5156 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5157 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005158 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5159 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005160 }
5161
Eric Laurenta121f902014-06-03 13:32:54 -07005162 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005163 if (config->type == AUDIO_PORT_TYPE_MIX) {
5164 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005165 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005166 if (outputDesc == NULL) {
5167 return BAD_VALUE;
5168 }
Eric Laurent84c70242014-06-23 08:46:27 -07005169 ALOG_ASSERT(!outputDesc->isDuplicated(),
5170 "setAudioPortConfig() called on duplicated output %d",
5171 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005172 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005173 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005174 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005175 if (inputDesc == NULL) {
5176 return BAD_VALUE;
5177 }
Eric Laurenta121f902014-06-03 13:32:54 -07005178 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005179 } else {
5180 return BAD_VALUE;
5181 }
5182 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5183 sp<DeviceDescriptor> deviceDesc;
5184 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5185 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5186 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5187 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5188 } else {
5189 return BAD_VALUE;
5190 }
5191 if (deviceDesc == NULL) {
5192 return BAD_VALUE;
5193 }
Eric Laurenta121f902014-06-03 13:32:54 -07005194 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005195 } else {
5196 return BAD_VALUE;
5197 }
5198
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005199 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005200 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5201 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005202 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005203 audioPortConfig->toAudioPortConfig(&newConfig, config);
5204 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005205 }
Eric Laurenta121f902014-06-03 13:32:54 -07005206 if (status != NO_ERROR) {
5207 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005208 }
Eric Laurente1715a42014-05-20 11:30:42 -07005209
5210 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005211}
5212
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005213void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5214{
Eric Laurentd60560a2015-04-10 11:31:20 -07005215 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005216 clearAudioPatches(uid);
5217 clearSessionRoutes(uid);
5218}
5219
Eric Laurent6a94d692014-05-20 11:18:06 -07005220void AudioPolicyManager::clearAudioPatches(uid_t uid)
5221{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005222 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005223 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005224 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005225 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005226 }
5227 }
5228}
5229
François Gaffiec005e562018-11-06 15:04:49 +01005230void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005231{
François Gaffiec005e562018-11-06 15:04:49 +01005232 // Take the first attributes following the product strategy as it is used to retrieve the routed
5233 // device. All attributes wihin a strategy follows the same "routing strategy"
5234 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5235 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005236 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005237 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005238 for (size_t j = 0; j < mOutputs.size(); j++) {
5239 if (mOutputs.keyAt(j) == ouptutToSkip) {
5240 continue;
5241 }
5242 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005243 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005244 continue;
5245 }
5246 // If the default device for this strategy is on another output mix,
5247 // invalidate all tracks in this strategy to force re connection.
5248 // Otherwise select new device on the output mix.
5249 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005250 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005251 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005252 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5253 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5254 // If the device is using preferred mixer attributes, the output need to reopen
5255 // with default configuration when the new selected devices are different from
5256 // current routing devices.
5257 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5258 continue;
5259 }
5260 setOutputDevices(outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005261 }
5262 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005263 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005264}
5265
5266void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5267{
5268 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005269 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005270 for (size_t i = 0; i < mOutputs.size(); i++) {
5271 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005272 for (const auto& client : outputDesc->getClientIterable()) {
5273 if (client->hasPreferredDevice() && client->uid() == uid) {
5274 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005275 auto clientStrategy = client->strategy();
5276 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5277 end(affectedStrategies)) {
5278 continue;
5279 }
5280 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005281 }
5282 }
5283 }
5284 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005285 for (const auto& strategy : affectedStrategies) {
5286 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005287 }
5288
5289 // remove input routes associated with this uid
5290 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005291 for (size_t i = 0; i < mInputs.size(); i++) {
5292 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005293 for (const auto& client : inputDesc->getClientIterable()) {
5294 if (client->hasPreferredDevice() && client->uid() == uid) {
5295 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5296 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005297 }
5298 }
5299 }
5300 // reroute inputs if necessary
5301 SortedVector<audio_io_handle_t> inputsToClose;
5302 for (size_t i = 0; i < mInputs.size(); i++) {
5303 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005304 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005305 inputsToClose.add(inputDesc->mIoHandle);
5306 }
5307 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005308 for (const auto& input : inputsToClose) {
5309 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005310 }
5311}
5312
Eric Laurentd60560a2015-04-10 11:31:20 -07005313void AudioPolicyManager::clearAudioSources(uid_t uid)
5314{
5315 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005316 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5317 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005318 stopAudioSource(mAudioSources.keyAt(i));
5319 }
5320 }
5321}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005322
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005323status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5324 audio_io_handle_t *ioHandle,
5325 audio_devices_t *device)
5326{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005327 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5328 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005329 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01005330 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005331
François Gaffiedf372692015-03-19 10:43:27 +01005332 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005333}
5334
Eric Laurentd60560a2015-04-10 11:31:20 -07005335status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005336 const audio_attributes_t *attributes,
5337 audio_port_handle_t *portId,
5338 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005339{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005340 ALOGV("%s", __FUNCTION__);
5341 *portId = AUDIO_PORT_HANDLE_NONE;
5342
5343 if (source == NULL || attributes == NULL || portId == NULL) {
5344 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5345 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005346 return BAD_VALUE;
5347 }
5348
Eric Laurentd60560a2015-04-10 11:31:20 -07005349 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5350 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005351 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5352 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005353 return INVALID_OPERATION;
5354 }
5355
François Gaffie11d30102018-11-02 16:09:09 +01005356 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005357 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005358 String8(source->ext.device.address),
5359 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005360 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005361 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005362 return BAD_VALUE;
5363 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005364
jiabin4ef93452019-09-10 14:29:54 -07005365 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005366
François Gaffieaaac0fd2018-11-22 17:56:39 +01005367 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005368 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005369 mEngine->getStreamTypeForAttributes(*attributes),
5370 mEngine->getProductStrategyForAttributes(*attributes),
5371 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005372
5373 status_t status = connectAudioSource(sourceDesc);
5374 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005375 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005376 }
5377 return status;
5378}
5379
Francois Gaffie601801d2021-06-22 13:27:39 +02005380sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5381 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5382{
5383 ALOGV("%s", __FUNCTION__);
5384 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5385
5386 status_t status = startAudioSource(source, attributes, &portId, uid);
5387 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5388 return mAudioSources.valueFor(portId);
5389}
5390
5391
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005392status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005393{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005394 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005395
5396 // make sure we only have one patch per source.
5397 disconnectAudioSource(sourceDesc);
5398
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005399 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005400 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5401 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5402 sourceDesc->srcDevice()->type(),
5403 String8(sourceDesc->srcDevice()->address().c_str()),
5404 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005405 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005406 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005407 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005408 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005409 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5410 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5411 return INVALID_OPERATION;
5412 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005413 PatchBuilder patchBuilder;
5414 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5415 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005416
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005417 return connectAudioSourceToSink(
5418 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005419}
5420
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005421status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005422{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005423 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5424 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005425 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005426 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005427 return BAD_VALUE;
5428 }
5429 status_t status = disconnectAudioSource(sourceDesc);
5430
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005431 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005432 return status;
5433}
5434
Andy Hung2ddee192015-12-18 17:34:44 -08005435status_t AudioPolicyManager::setMasterMono(bool mono)
5436{
5437 if (mMasterMono == mono) {
5438 return NO_ERROR;
5439 }
5440 mMasterMono = mono;
5441 // if enabling mono we close all offloaded devices, which will invalidate the
5442 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5443 // for recreating the new AudioTrack as non-offloaded PCM.
5444 //
5445 // If disabling mono, we leave all tracks as is: we don't know which clients
5446 // and tracks are able to be recreated as offloaded. The next "song" should
5447 // play back offloaded.
5448 if (mMasterMono) {
5449 Vector<audio_io_handle_t> offloaded;
5450 for (size_t i = 0; i < mOutputs.size(); ++i) {
5451 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5452 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5453 offloaded.push(desc->mIoHandle);
5454 }
5455 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005456 for (const auto& handle : offloaded) {
5457 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005458 }
5459 }
5460 // update master mono for all remaining outputs
5461 for (size_t i = 0; i < mOutputs.size(); ++i) {
5462 updateMono(mOutputs.keyAt(i));
5463 }
5464 return NO_ERROR;
5465}
5466
5467status_t AudioPolicyManager::getMasterMono(bool *mono)
5468{
5469 *mono = mMasterMono;
5470 return NO_ERROR;
5471}
5472
Eric Laurentac9cef52017-06-09 15:46:26 -07005473float AudioPolicyManager::getStreamVolumeDB(
5474 audio_stream_type_t stream, int index, audio_devices_t device)
5475{
jiabin9a3361e2019-10-01 09:38:30 -07005476 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005477}
5478
jiabin81772902018-04-02 17:52:27 -07005479status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5480 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005481 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005482{
Kriti Dang6537def2021-03-02 13:46:59 +01005483 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5484 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005485 return BAD_VALUE;
5486 }
Kriti Dang6537def2021-03-02 13:46:59 +01005487 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5488 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005489
5490 size_t formatsWritten = 0;
5491 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005492
Kriti Dang6537def2021-03-02 13:46:59 +01005493 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005494 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5495 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005496 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005497 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005498 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005499 bool formatEnabled = true;
5500 switch (forceUse) {
5501 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005502 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005503 break;
5504 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5505 formatEnabled = false;
5506 break;
5507 default: // AUTO or ALWAYS => true
5508 break;
jiabin81772902018-04-02 17:52:27 -07005509 }
5510 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5511 }
jiabin81772902018-04-02 17:52:27 -07005512 }
5513 return NO_ERROR;
5514}
5515
Kriti Dang6537def2021-03-02 13:46:59 +01005516status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5517 audio_format_t *surroundFormats) {
5518 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5519 return BAD_VALUE;
5520 }
5521 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5522 __func__, *numSurroundFormats, surroundFormats);
5523
5524 size_t formatsWritten = 0;
5525 size_t formatsMax = *numSurroundFormats;
5526 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5527
5528 // Return formats from all device profiles that have already been resolved by
5529 // checkOutputsForDevice().
5530 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5531 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5532 audio_devices_t deviceType = device->type();
5533 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5534 // returns formats reported by HDMI devices.
5535 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5536 continue;
5537 }
5538 // Formats reported by sink devices
5539 std::unordered_set<audio_format_t> formatset;
5540 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5541 formatset.insert(it->second.begin(), it->second.end());
5542 }
5543
5544 // Formats hard-coded in the in policy configuration file (if any).
5545 FormatVector encodedFormats = device->encodedFormats();
5546 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5547 // Filter the formats which are supported by the vendor hardware.
5548 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5549 if (mConfig.getSurroundFormats().count(*it) != 0) {
5550 formats.insert(*it);
5551 } else {
5552 for (const auto& pair : mConfig.getSurroundFormats()) {
5553 if (pair.second.count(*it) != 0) {
5554 formats.insert(pair.first);
5555 break;
5556 }
5557 }
5558 }
5559 }
5560 }
5561 *numSurroundFormats = formats.size();
5562 for (const auto& format: formats) {
5563 if (formatsWritten < formatsMax) {
5564 surroundFormats[formatsWritten++] = format;
5565 }
5566 }
5567 return NO_ERROR;
5568}
5569
jiabin81772902018-04-02 17:52:27 -07005570status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5571{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005572 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005573 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5574 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005575 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005576 return BAD_VALUE;
5577 }
5578
Mikhail Naganov100f0122018-11-29 11:22:16 -08005579 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5580 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005581 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005582 return INVALID_OPERATION;
5583 }
5584
Mikhail Naganov100f0122018-11-29 11:22:16 -08005585 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005586 return NO_ERROR;
5587 }
5588
Mikhail Naganov100f0122018-11-29 11:22:16 -08005589 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005590 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005591 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005592 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005593 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005594 }
5595 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005596 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005597 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005598 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005599 }
5600 }
5601
5602 sp<SwAudioOutputDescriptor> outputDesc;
5603 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005604 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5605 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005606 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5607 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005608 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005609 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005610 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5611 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5612 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005613 name.c_str(),
5614 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005615 if (status != NO_ERROR) {
5616 continue;
5617 }
5618 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5619 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5620 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005621 name.c_str(),
5622 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005623 profileUpdated |= (status == NO_ERROR);
5624 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005625 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005626 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005627 AUDIO_DEVICE_IN_HDMI);
5628 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5629 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005630 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005631 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005632 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5633 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5634 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005635 name.c_str(),
5636 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005637 if (status != NO_ERROR) {
5638 continue;
5639 }
5640 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5641 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5642 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005643 name.c_str(),
5644 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005645 profileUpdated |= (status == NO_ERROR);
5646 }
5647
jiabin81772902018-04-02 17:52:27 -07005648 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005649 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005650 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005651 }
5652
5653 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5654}
5655
Eric Laurent5ada82e2019-08-29 17:53:54 -07005656void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005657{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005658 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005659 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005660 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005661 }
5662}
5663
jiabin6012f912018-11-02 17:06:30 -07005664bool AudioPolicyManager::isHapticPlaybackSupported()
5665{
5666 for (const auto& hwModule : mHwModules) {
5667 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5668 for (const auto &outProfile : outputProfiles) {
5669 struct audio_port audioPort;
5670 outProfile->toAudioPort(&audioPort);
5671 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5672 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5673 return true;
5674 }
5675 }
5676 }
5677 }
5678 return false;
5679}
5680
Carter Hsu325a8eb2022-01-19 19:56:51 +08005681bool AudioPolicyManager::isUltrasoundSupported()
5682{
5683 bool hasUltrasoundOutput = false;
5684 bool hasUltrasoundInput = false;
5685 for (const auto& hwModule : mHwModules) {
5686 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5687 if (!hasUltrasoundOutput) {
5688 for (const auto &outProfile : outputProfiles) {
5689 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5690 hasUltrasoundOutput = true;
5691 break;
5692 }
5693 }
5694 }
5695
5696 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5697 if (!hasUltrasoundInput) {
5698 for (const auto &inputProfile : inputProfiles) {
5699 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5700 hasUltrasoundInput = true;
5701 break;
5702 }
5703 }
5704 }
5705
5706 if (hasUltrasoundOutput && hasUltrasoundInput)
5707 return true;
5708 }
5709 return false;
5710}
5711
Atneya Nair698f5ef2022-12-15 16:15:09 -08005712bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5713{
5714 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5715 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5716 for (const auto& hwModule : mHwModules) {
5717 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5718 for (const auto &inputProfile : inputProfiles) {
5719 if ((inputProfile->getFlags() & mask) == mask) {
5720 return true;
5721 }
5722 }
5723 }
5724 return false;
5725}
5726
Eric Laurent8340e672019-11-06 11:01:08 -08005727bool AudioPolicyManager::isCallScreenModeSupported()
5728{
5729 return getConfig().isCallScreenModeSupported();
5730}
5731
5732
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005733status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005734{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005735 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005736 if (!sourceDesc->isConnected()) {
5737 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5738 return NO_ERROR;
5739 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005740 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5741 if (swOutput != 0) {
5742 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005743 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005744 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005745 }
jiabinbce0c1d2020-10-05 11:20:18 -07005746 if (releaseOutput(sourceDesc->portId())) {
5747 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5748 // no need to release audio patch here but just return NO_ERROR.
5749 return NO_ERROR;
5750 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005751 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005752 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005753 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005754 // close Hwoutput and remove from mHwOutputs
5755 } else {
5756 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5757 }
5758 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005759 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005760 sourceDesc->disconnect();
5761 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005762}
5763
François Gaffiec005e562018-11-06 15:04:49 +01005764sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5765 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005766{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005767 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005768 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005769 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005770 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005771 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5772 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005773 source = sourceDesc;
5774 break;
5775 }
5776 }
5777 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005778}
5779
Eric Laurentb4f42a92022-01-17 17:37:31 +01005780bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005781 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005782 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005783{
5784 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5785 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005786 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005787 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005788 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5789 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5790 return false;
5791 }
5792 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5793 return false;
5794 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005795 }
5796
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005797 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005798 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005799 if (profile == nullptr) {
5800 return false;
5801 }
5802
5803 // The caller can have the audio config criteria ignored by either passing a null ptr or
5804 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005805 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005806 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005807
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005808 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005809 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005810 return false;
5811 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005812 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005813 return true;
5814}
5815
5816void AudioPolicyManager::checkVirtualizerClientRoutes() {
5817 std::set<audio_stream_type_t> streamsToInvalidate;
5818 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005819 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5820 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005821 audio_attributes_t attr = client->attributes();
5822 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5823 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5824 audio_config_base_t clientConfig = client->config();
5825 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005826 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005827 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005828 streamsToInvalidate.insert(client->stream());
5829 }
5830 }
5831 }
5832
jiabinc44b3462022-12-08 12:52:31 -08005833 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005834}
5835
Eric Laurente191d1b2022-04-15 11:59:25 +02005836
5837bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5838 const sp<SwAudioOutputDescriptor>& outputDesc) {
5839 if (outputDesc->isDuplicated()) {
5840 return false;
5841 }
5842 DeviceVector devices = outputDesc->supportedDevices();
5843 for (size_t i = 0; i < mOutputs.size(); i++) {
5844 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5845 if (desc == outputDesc || desc->isDuplicated()) {
5846 continue;
5847 }
5848 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5849 if (!sharedDevices.isEmpty()
5850 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5851 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5852 return false;
5853 }
5854 }
5855 return true;
5856}
5857
5858
Eric Laurentfa0f6742021-08-17 18:39:44 +02005859status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005860 const audio_attributes_t *attr,
5861 audio_io_handle_t *output) {
5862 *output = AUDIO_IO_HANDLE_NONE;
5863
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005864 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5865 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5866 audio_config_t *configPtr = nullptr;
5867 audio_config_t config;
5868 if (mixerConfig != nullptr) {
5869 config = audio_config_initializer(mixerConfig);
5870 configPtr = &config;
5871 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005872 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005873 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005874 return BAD_VALUE;
5875 }
5876
5877 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005878 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005879 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005880 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005881 return BAD_VALUE;
5882 }
5883
Eric Laurente191d1b2022-04-15 11:59:25 +02005884 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005885 for (size_t i = 0; i < mOutputs.size(); i++) {
5886 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005887 if (!desc->isDuplicated()
5888 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5889 spatializerOutputs.push_back(desc);
5890 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005891 }
5892 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005893 mSpatializerOutput.clear();
5894 bool outputsChanged = false;
5895 for (const auto& desc : spatializerOutputs) {
5896 if (desc->mProfile == profile
5897 && (configPtr == nullptr
5898 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5899 mSpatializerOutput = desc;
5900 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5901 } else {
5902 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5903 " and devices %s", __func__, desc->mIoHandle,
5904 configPtr != nullptr ? configPtr->channel_mask : 0,
5905 devices.toString().c_str());
5906 closeOutput(desc->mIoHandle);
5907 outputsChanged = true;
5908 }
Eric Laurent39095982021-08-24 18:29:27 +02005909 }
5910
Eric Laurente191d1b2022-04-15 11:59:25 +02005911 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005912 sp<SwAudioOutputDescriptor> desc =
5913 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005914 if (desc != nullptr) {
5915 mSpatializerOutput = desc;
5916 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005917 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005918 }
5919
5920 checkVirtualizerClientRoutes();
5921
Eric Laurente191d1b2022-04-15 11:59:25 +02005922 if (outputsChanged) {
5923 mPreviousOutputs = mOutputs;
5924 mpClientInterface->onAudioPortListUpdate();
5925 }
5926
5927 if (mSpatializerOutput == nullptr) {
5928 ALOGV("%s could not open spatializer output with requested config", __func__);
5929 return BAD_VALUE;
5930 }
Eric Laurent39095982021-08-24 18:29:27 +02005931 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005932 ALOGV("%s returning new spatializer output %d", __func__, *output);
5933 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005934}
5935
Eric Laurentfa0f6742021-08-17 18:39:44 +02005936status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5937 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005938 return INVALID_OPERATION;
5939 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005940 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005941 return BAD_VALUE;
5942 }
Eric Laurent39095982021-08-24 18:29:27 +02005943
Eric Laurente191d1b2022-04-15 11:59:25 +02005944 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5945 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5946 closeOutput(mSpatializerOutput->mIoHandle);
5947 //from now on mSpatializerOutput is null
5948 checkVirtualizerClientRoutes();
5949 }
Eric Laurent39095982021-08-24 18:29:27 +02005950
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005951 return NO_ERROR;
5952}
5953
Eric Laurente552edb2014-03-10 17:42:56 -07005954// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005955// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005956// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005957uint32_t AudioPolicyManager::nextAudioPortGeneration()
5958{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005959 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005960}
5961
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005962static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005963 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5964 !audioPolicyXmlConfigFile.empty()) {
5965 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5966 if (ret == NO_ERROR) {
5967 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005968 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005969 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005970 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005971 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005972}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005973
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005974AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5975 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005976 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005977 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005978 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005979 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005980 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005981 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005982 mAudioPortGeneration(1),
5983 mBeaconMuteRefCount(0),
5984 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005985 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005986 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005987 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005988 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005989{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005990}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005991
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005992AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5993 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5994{
5995 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005996}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005997
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005998void AudioPolicyManager::loadConfig() {
5999 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01006000 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006001 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01006002 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006003}
6004
6005status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07006006 {
6007 auto engLib = EngineLibrary::load(
6008 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
6009 if (!engLib) {
6010 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
6011 return NO_INIT;
6012 }
6013 mEngine = engLib->createEngine();
6014 if (mEngine == nullptr) {
6015 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
6016 return NO_INIT;
6017 }
François Gaffie2110e042015-03-24 08:41:51 +01006018 }
6019 mEngine->setObserver(this);
6020 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006021 if (status != NO_ERROR) {
6022 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6023 return status;
6024 }
François Gaffie2110e042015-03-24 08:41:51 +01006025
Mikhail Naganove93ae282023-02-02 15:28:26 -08006026 // If microphones address is empty, set it according to device type
6027 for (size_t i = 0; i < mInputDevicesAll.size(); i++) {
6028 if (mInputDevicesAll[i]->address().empty()) {
6029 if (mInputDevicesAll[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
6030 mInputDevicesAll[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
6031 } else if (mInputDevicesAll[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
6032 mInputDevicesAll[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
6033 }
6034 }
6035 }
6036
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006037 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006038 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6039 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6040
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006041 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006042 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006043 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006044
Eric Laurent3a4311c2014-03-17 12:00:47 -07006045 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01006046 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
6047 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
6048 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006049 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006050 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006051 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006052
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006053 // Silence ALOGV statements
6054 property_set("log.tag." LOG_TAG, "D");
6055
Eric Laurente552edb2014-03-10 17:42:56 -07006056 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006057 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006058}
6059
Eric Laurente0720872014-03-11 09:30:41 -07006060AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006061{
Eric Laurente552edb2014-03-10 17:42:56 -07006062 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006063 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006064 }
6065 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006066 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006067 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006068 mAvailableOutputDevices.clear();
6069 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006070 mOutputs.clear();
6071 mInputs.clear();
6072 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08006073 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006074 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006075}
6076
Eric Laurente0720872014-03-11 09:30:41 -07006077status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006078{
Eric Laurent87ffa392015-05-22 10:32:38 -07006079 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006080}
6081
Eric Laurente552edb2014-03-10 17:42:56 -07006082// ---
6083
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006084void AudioPolicyManager::onNewAudioModulesAvailable()
6085{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006086 DeviceVector newDevices;
6087 onNewAudioModulesAvailableInt(&newDevices);
6088 if (!newDevices.empty()) {
6089 nextAudioPortGeneration();
6090 mpClientInterface->onAudioPortListUpdate();
6091 }
6092}
6093
6094void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6095{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006096 for (const auto& hwModule : mHwModulesAll) {
6097 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6098 continue;
6099 }
6100 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
6101 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
6102 ALOGW("could not open HW module %s", hwModule->getName());
6103 continue;
6104 }
6105 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006106 // open all output streams needed to access attached devices.
6107 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006108 // This also validates mAvailableOutputDevices list
6109 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6110 if (!outProfile->canOpenNewIo()) {
6111 ALOGE("Invalid Output profile max open count %u for profile %s",
6112 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6113 continue;
6114 }
6115 if (!outProfile->hasSupportedDevices()) {
6116 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6117 continue;
6118 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006119 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6120 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006121 mTtsOutputAvailable = true;
6122 }
6123
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006124 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
6125 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
6126 sp<DeviceDescriptor> supportedDevice = 0;
6127 if (supportedDevices.contains(mDefaultOutputDevice)) {
6128 supportedDevice = mDefaultOutputDevice;
6129 } else {
6130 // choose first device present in profile's SupportedDevices also part of
6131 // mAvailableOutputDevices.
6132 if (availProfileDevices.isEmpty()) {
6133 continue;
6134 }
6135 supportedDevice = availProfileDevices.itemAt(0);
6136 }
6137 if (!mOutputDevicesAll.contains(supportedDevice)) {
6138 continue;
6139 }
6140 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6141 mpClientInterface);
6142 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006143 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6144 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006145 AUDIO_STREAM_DEFAULT,
6146 AUDIO_OUTPUT_FLAG_NONE, &output);
6147 if (status != NO_ERROR) {
6148 ALOGW("Cannot open output stream for devices %s on hw module %s",
6149 supportedDevice->toString().c_str(), hwModule->getName());
6150 continue;
6151 }
6152 for (const auto &device : availProfileDevices) {
6153 // give a valid ID to an attached device once confirmed it is reachable
6154 if (!device->isAttached()) {
6155 device->attach(hwModule);
6156 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006157 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006158 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006159 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6160 }
6161 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006162 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006163 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6164 mPrimaryOutput = outputDesc;
6165 }
Eric Laurent39095982021-08-24 18:29:27 +02006166 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006167 outputDesc->close();
6168 } else {
6169 addOutput(output, outputDesc);
6170 setOutputDevices(outputDesc,
6171 DeviceVector(supportedDevice),
6172 true,
6173 0,
6174 NULL);
6175 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006176 }
6177 // open input streams needed to access attached devices to validate
6178 // mAvailableInputDevices list
6179 for (const auto& inProfile : hwModule->getInputProfiles()) {
6180 if (!inProfile->canOpenNewIo()) {
6181 ALOGE("Invalid Input profile max open count %u for profile %s",
6182 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6183 continue;
6184 }
6185 if (!inProfile->hasSupportedDevices()) {
6186 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6187 continue;
6188 }
6189 // chose first device present in profile's SupportedDevices also part of
6190 // available input devices
6191 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
6192 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
6193 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006194 ALOGV("%s: Input device list is empty! for profile %s",
6195 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006196 continue;
6197 }
6198 sp<AudioInputDescriptor> inputDesc =
6199 new AudioInputDescriptor(inProfile, mpClientInterface);
6200
6201 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6202 status_t status = inputDesc->open(nullptr,
6203 availProfileDevices.itemAt(0),
6204 AUDIO_SOURCE_MIC,
6205 AUDIO_INPUT_FLAG_NONE,
6206 &input);
6207 if (status != NO_ERROR) {
6208 ALOGW("Cannot open input stream for device %s on hw module %s",
6209 availProfileDevices.toString().c_str(),
6210 hwModule->getName());
6211 continue;
6212 }
6213 for (const auto &device : availProfileDevices) {
6214 // give a valid ID to an attached device once confirmed it is reachable
6215 if (!device->isAttached()) {
6216 device->attach(hwModule);
6217 device->importAudioPortAndPickAudioProfile(inProfile, true);
6218 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006219 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006220 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6221 }
6222 }
6223 inputDesc->close();
6224 }
6225 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006226
6227 // Check if spatializer outputs can be closed until used.
6228 // mOutputs vector never contains duplicated outputs at this point.
6229 std::vector<audio_io_handle_t> outputsClosed;
6230 for (size_t i = 0; i < mOutputs.size(); i++) {
6231 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6232 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6233 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6234 outputsClosed.push_back(desc->mIoHandle);
6235 desc->close();
6236 }
6237 }
6238 for (auto output : outputsClosed) {
6239 removeOutput(output);
6240 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006241}
6242
Eric Laurent98e38192018-02-15 18:31:53 -08006243void AudioPolicyManager::addOutput(audio_io_handle_t output,
6244 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006245{
Eric Laurent1c333e22014-05-20 10:48:17 -07006246 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006247 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006248 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006249 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006250 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006251}
6252
François Gaffie53615e22015-03-19 09:24:12 +01006253void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6254{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006255 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6256 ALOGV("%s: removing primary output", __func__);
6257 mPrimaryOutput = nullptr;
6258 }
François Gaffie53615e22015-03-19 09:24:12 +01006259 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006260 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006261}
6262
Eric Laurent98e38192018-02-15 18:31:53 -08006263void AudioPolicyManager::addInput(audio_io_handle_t input,
6264 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006265{
Eric Laurent1c333e22014-05-20 10:48:17 -07006266 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006267 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006268}
Eric Laurente552edb2014-03-10 17:42:56 -07006269
François Gaffie11d30102018-11-02 16:09:09 +01006270status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006271 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006272 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006273{
François Gaffie11d30102018-11-02 16:09:09 +01006274 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006275 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006276 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006277
François Gaffie11d30102018-11-02 16:09:09 +01006278 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006279 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006280 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006281 }
Eric Laurente552edb2014-03-10 17:42:56 -07006282
Eric Laurent3b73df72014-03-11 09:06:29 -07006283 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006284 // first call getAudioPort to get the supported attributes from the HAL
6285 struct audio_port_v7 port = {};
6286 device->toAudioPort(&port);
6287 status_t status = mpClientInterface->getAudioPort(&port);
6288 if (status == NO_ERROR) {
6289 device->importAudioPort(port);
6290 }
6291
6292 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006293 for (size_t i = 0; i < mOutputs.size(); i++) {
6294 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006295 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006296 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006297 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6298 mOutputs.keyAt(i), device->toString().c_str());
6299 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006300 }
6301 }
6302 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006303 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006304 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006305 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6306 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006307 if (profile->supportsDevice(device)) {
6308 profiles.add(profile);
6309 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6310 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006311 }
6312 }
6313 }
6314
Eric Laurent7b279bb2015-12-14 10:18:23 -08006315 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006316
Eric Laurente552edb2014-03-10 17:42:56 -07006317 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006318 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006319 return BAD_VALUE;
6320 }
6321
6322 // open outputs for matching profiles if needed. Direct outputs are also opened to
6323 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6324 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006325 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006326
6327 // nothing to do if one output is already opened for this profile
6328 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006329 for (j = 0; j < outputs.size(); j++) {
6330 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006331 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006332 // matching profile: save the sample rates, format and channel masks supported
6333 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006334 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006335 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006336 }
Eric Laurente552edb2014-03-10 17:42:56 -07006337 break;
6338 }
6339 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006340 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006341 continue;
6342 }
6343
Eric Laurent3974e3b2017-12-07 17:58:43 -08006344 if (!profile->canOpenNewIo()) {
6345 ALOGW("Max Output number %u already opened for this profile %s",
6346 profile->maxOpenCount, profile->getTagName().c_str());
6347 continue;
6348 }
6349
Eric Laurent83efe1c2017-07-09 16:51:08 -07006350 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07006351 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006352 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6353 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006354 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006355 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006356 profiles.removeAt(profile_index);
6357 profile_index--;
6358 } else {
6359 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006360 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006361 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006362 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6363 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006364 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006365 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006366
François Gaffie11d30102018-11-02 16:09:09 +01006367 if (device_distinguishes_on_address(deviceType)) {
6368 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6369 device->toString().c_str());
6370 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
6371 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006372 }
Eric Laurente552edb2014-03-10 17:42:56 -07006373 ALOGV("checkOutputsForDevice(): adding output %d", output);
6374 }
6375 }
6376
6377 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006378 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006379 return BAD_VALUE;
6380 }
Eric Laurentd4692962014-05-05 18:13:44 -07006381 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006382 // check if one opened output is not needed any more after disconnecting one device
6383 for (size_t i = 0; i < mOutputs.size(); i++) {
6384 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006385 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006386 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006387 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006388 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006389 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006390 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006391 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6392 mOutputs.keyAt(i));
6393 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006394 }
Eric Laurente552edb2014-03-10 17:42:56 -07006395 }
6396 }
Eric Laurentd4692962014-05-05 18:13:44 -07006397 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006398 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006399 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6400 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006401 if (!profile->supportsDevice(device)) {
6402 continue;
6403 }
6404 ALOGV("checkOutputsForDevice(): "
6405 "clearing direct output profile %zu on module %s",
6406 j, hwModule->getName());
6407 profile->clearAudioProfiles();
6408 if (!profile->hasDynamicAudioProfile()) {
6409 continue;
6410 }
6411 // When a device is disconnected, if there is an IOProfile that contains dynamic
6412 // profiles and supports the disconnected device, call getAudioPort to repopulate
6413 // the capabilities of the devices that is supported by the IOProfile.
6414 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6415 if (supportedDevice == device ||
6416 !mAvailableOutputDevices.contains(supportedDevice)) {
6417 continue;
6418 }
6419 struct audio_port_v7 port;
6420 supportedDevice->toAudioPort(&port);
6421 status_t status = mpClientInterface->getAudioPort(&port);
6422 if (status == NO_ERROR) {
6423 supportedDevice->importAudioPort(port);
6424 }
Eric Laurente552edb2014-03-10 17:42:56 -07006425 }
6426 }
6427 }
6428 }
6429 return NO_ERROR;
6430}
6431
François Gaffie11d30102018-11-02 16:09:09 +01006432status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006433 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006434{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006435 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006436
François Gaffie11d30102018-11-02 16:09:09 +01006437 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006438 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006439 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006440 }
6441
Eric Laurentd4692962014-05-05 18:13:44 -07006442 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006443 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006444 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006445 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006446 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006447 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006448 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006449 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006450
François Gaffie11d30102018-11-02 16:09:09 +01006451 if (profile->supportsDevice(device)) {
6452 profiles.add(profile);
6453 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6454 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006455 }
6456 }
6457 }
6458
Eric Laurent0dd51852019-04-19 18:18:58 -07006459 if (profiles.isEmpty()) {
6460 ALOGW("%s: No input profile available for device %s",
6461 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006462 return BAD_VALUE;
6463 }
6464
6465 // open inputs for matching profiles if needed. Direct inputs are also opened to
6466 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6467 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6468
Eric Laurent1c333e22014-05-20 10:48:17 -07006469 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006470
Eric Laurentd4692962014-05-05 18:13:44 -07006471 // nothing to do if one input is already opened for this profile
6472 size_t input_index;
6473 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6474 desc = mInputs.valueAt(input_index);
6475 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006476 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006477 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006478 }
Eric Laurentd4692962014-05-05 18:13:44 -07006479 break;
6480 }
6481 }
6482 if (input_index != mInputs.size()) {
6483 continue;
6484 }
6485
Eric Laurent3974e3b2017-12-07 17:58:43 -08006486 if (!profile->canOpenNewIo()) {
6487 ALOGW("Max Input number %u already opened for this profile %s",
6488 profile->maxOpenCount, profile->getTagName().c_str());
6489 continue;
6490 }
6491
Eric Laurentfe231122017-11-17 17:48:06 -08006492 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006493 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006494 status_t status = desc->open(nullptr,
6495 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006496 AUDIO_SOURCE_MIC,
6497 AUDIO_INPUT_FLAG_NONE,
6498 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006499
Eric Laurentcf2c0212014-07-25 16:20:43 -07006500 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006501 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006502 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006503 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006504 mpClientInterface->setParameters(input, String8(param));
6505 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006506 }
François Gaffie11d30102018-11-02 16:09:09 +01006507 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006508 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006509 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006510 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006511 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006512 }
6513
Eric Laurent0dd51852019-04-19 18:18:58 -07006514 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006515 addInput(input, desc);
6516 }
6517 } // endif input != 0
6518
Eric Laurentcf2c0212014-07-25 16:20:43 -07006519 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006520 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006521 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006522 profiles.removeAt(profile_index);
6523 profile_index--;
6524 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006525 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006526 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006527 }
Eric Laurentd4692962014-05-05 18:13:44 -07006528 ALOGV("checkInputsForDevice(): adding input %d", input);
6529 }
6530 } // end scan profiles
6531
6532 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006533 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006534 return BAD_VALUE;
6535 }
6536 } else {
6537 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006538 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006539 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006540 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006541 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006542 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006543 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006544 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006545 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6546 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006547 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006548 }
6549 }
6550 }
6551 } // end disconnect
6552
6553 return NO_ERROR;
6554}
6555
6556
Eric Laurente0720872014-03-11 09:30:41 -07006557void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006558{
6559 ALOGV("closeOutput(%d)", output);
6560
François Gaffie1c878552018-11-22 16:53:21 +01006561 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6562 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006563 ALOGW("closeOutput() unknown output %d", output);
6564 return;
6565 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006566 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006567 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006568
Eric Laurente552edb2014-03-10 17:42:56 -07006569 // look for duplicated outputs connected to the output being removed.
6570 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006571 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6572 if (dupOutput->isDuplicated() &&
6573 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6574 sp<SwAudioOutputDescriptor> remainingOutput =
6575 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006576 // As all active tracks on duplicated output will be deleted,
6577 // and as they were also referenced on the other output, the reference
6578 // count for their stream type must be adjusted accordingly on
6579 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006580 const bool wasActive = remainingOutput->isActive();
6581 // Note: no-op on the closing output where all clients has already been set inactive
6582 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006583 // stop() will be a no op if the output is still active but is needed in case all
6584 // active streams refcounts where cleared above
6585 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006586 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006587 }
Eric Laurente552edb2014-03-10 17:42:56 -07006588 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6589 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6590
6591 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006592 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006593 }
6594 }
6595
Eric Laurent05b90f82014-08-27 15:32:29 -07006596 nextAudioPortGeneration();
6597
François Gaffie1c878552018-11-22 16:53:21 +01006598 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006599 if (index >= 0) {
6600 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006601 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6602 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006603 mAudioPatches.removeItemsAt(index);
6604 mpClientInterface->onAudioPatchListUpdate();
6605 }
6606
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006607 if (closingOutputWasActive) {
6608 closingOutput->stop();
6609 }
François Gaffie1c878552018-11-22 16:53:21 +01006610 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006611
François Gaffie53615e22015-03-19 09:24:12 +01006612 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006613 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006614 if (closingOutput == mSpatializerOutput) {
6615 mSpatializerOutput.clear();
6616 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006617
6618 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6619 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006620 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006621 bool directOutputOpen = false;
6622 for (size_t i = 0; i < mOutputs.size(); i++) {
6623 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6624 directOutputOpen = true;
6625 break;
6626 }
6627 }
6628 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006629 ALOGV("no direct outputs open, reset MSD patches");
6630 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6631 // how output devices for patching are resolved. Avoid by caching and reusing the
6632 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6633 // devices to patch to. This may be complicated by the fact that devices may become
6634 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006635 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006636 }
6637 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006638}
6639
6640void AudioPolicyManager::closeInput(audio_io_handle_t input)
6641{
6642 ALOGV("closeInput(%d)", input);
6643
6644 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6645 if (inputDesc == NULL) {
6646 ALOGW("closeInput() unknown input %d", input);
6647 return;
6648 }
6649
Eric Laurent6a94d692014-05-20 11:18:06 -07006650 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006651
François Gaffie11d30102018-11-02 16:09:09 +01006652 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006653 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006654 if (index >= 0) {
6655 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006656 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6657 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006658 mAudioPatches.removeItemsAt(index);
6659 mpClientInterface->onAudioPatchListUpdate();
6660 }
6661
Eric Laurentfe231122017-11-17 17:48:06 -08006662 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006663 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006664
François Gaffie11d30102018-11-02 16:09:09 +01006665 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6666 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006667 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006668 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006669 }
Eric Laurente552edb2014-03-10 17:42:56 -07006670}
6671
François Gaffie11d30102018-11-02 16:09:09 +01006672SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6673 const DeviceVector &devices,
6674 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006675{
6676 SortedVector<audio_io_handle_t> outputs;
6677
François Gaffie11d30102018-11-02 16:09:09 +01006678 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006679 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006680 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006681 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006682 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006683 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006684 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006685 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006686 outputs.add(openOutputs.keyAt(i));
6687 }
6688 }
6689 return outputs;
6690}
6691
Mikhail Naganov37977152018-07-11 15:54:44 -07006692void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6693{
6694 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6695 // output is suspended before any tracks are moved to it
6696 checkA2dpSuspend();
6697 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006698 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006699 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006700 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006701 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006702 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6703 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6704 // configuration changes will ultimately be rerouted correctly. We can still avoid
6705 // unnecessary rerouting by caching and reusing the arguments to
6706 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6707 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006708 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006709 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006710 // an event that changed routing likely occurred, inform upper layers
6711 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006712}
6713
François Gaffiec005e562018-11-06 15:04:49 +01006714bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6715 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006716{
François Gaffiec005e562018-11-06 15:04:49 +01006717 return mEngine->getProductStrategyForAttributes(lAttr) ==
6718 mEngine->getProductStrategyForAttributes(rAttr);
6719}
6720
Francois Gaffieff1eb522020-05-06 18:37:04 +02006721void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6722{
6723 for (size_t i = 0; i < mAudioSources.size(); i++) {
6724 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6725 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006726 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006727 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006728 connectAudioSource(sourceDesc);
6729 }
6730 }
6731}
6732
6733void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6734{
6735 for (size_t i = 0; i < mAudioSources.size(); i++) {
6736 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6737 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6738 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6739 disconnectAudioSource(sourceDesc);
6740 }
6741 }
6742}
6743
François Gaffiec005e562018-11-06 15:04:49 +01006744void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6745{
6746 auto psId = mEngine->getProductStrategyForAttributes(attr);
6747
6748 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6749 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006750
François Gaffie11d30102018-11-02 16:09:09 +01006751 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6752 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006753
Eric Laurentc209fe42020-06-05 18:11:23 -07006754 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006755 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006756 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006757 // take into account dynamic audio policies related changes: if a client is now associated
6758 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006759 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006760 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6761 if (desc->isDuplicated()) {
6762 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006763 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006764 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6765 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6766 continue;
6767 }
6768 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006769 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006770 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6771 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6772 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006773 if (status != OK) {
6774 continue;
6775 }
yucliuf4de36d2020-09-14 14:57:56 -07006776 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006777 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006778 maxLatency = desc->latency();
6779 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006780 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006781 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006782 }
6783 }
6784
Eric Laurent56ed8842022-11-15 16:04:41 +01006785 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006786 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6787 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006788 for (audio_io_handle_t srcOut : srcOutputs) {
6789 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006790 if (desc == nullptr) continue;
6791
6792 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006793 maxLatency = desc->latency();
6794 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006795
Eric Laurent56ed8842022-11-15 16:04:41 +01006796 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006797 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006798 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006799 // a client on a non direct outputs has necessarily a linear PCM format
6800 // so we can call selectOutput() safely
6801 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6802 client->flags(),
6803 client->config().format,
6804 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006805 client->config().sample_rate,
6806 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006807 if (newOutput != srcOut) {
6808 invalidate = true;
6809 break;
6810 }
6811 } else {
6812 sp<IOProfile> profile = getProfileForOutput(newDevices,
6813 client->config().sample_rate,
6814 client->config().format,
6815 client->config().channel_mask,
6816 client->flags(),
6817 true /* directOnly */);
6818 if (profile != desc->mProfile) {
6819 invalidate = true;
6820 break;
6821 }
6822 }
6823 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006824 // mute strategy while moving tracks from one output to another
6825 if (invalidate) {
6826 invalidatedOutputs.push_back(desc);
6827 if (desc->isStrategyActive(psId)) {
6828 setStrategyMute(psId, true, desc);
6829 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6830 newDevices.types());
6831 }
Eric Laurente552edb2014-03-10 17:42:56 -07006832 }
François Gaffiec005e562018-11-06 15:04:49 +01006833 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006834 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006835 connectAudioSource(source);
6836 }
Eric Laurente552edb2014-03-10 17:42:56 -07006837 }
6838
Eric Laurent56ed8842022-11-15 16:04:41 +01006839 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6840 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6841 std::to_string(srcOutputs[0]).c_str(),
6842 std::to_string(dstOutputs[0]).c_str());
6843
François Gaffiec005e562018-11-06 15:04:49 +01006844 // Move effects associated to this stream from previous output to new output
6845 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006846 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006847 }
François Gaffiec005e562018-11-06 15:04:49 +01006848 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006849 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006850 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006851 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006852 desc->setTracksInvalidatedStatusByStrategy(psId);
6853 }
Eric Laurente552edb2014-03-10 17:42:56 -07006854 }
6855 }
6856}
6857
Eric Laurente0720872014-03-11 09:30:41 -07006858void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006859{
François Gaffiec005e562018-11-06 15:04:49 +01006860 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6861 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6862 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006863 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006864 }
Eric Laurente552edb2014-03-10 17:42:56 -07006865}
6866
Kevin Rocard153f92d2018-12-18 18:33:28 -08006867void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08006868 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006869 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006870 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006871 for (size_t i = 0; i < mOutputs.size(); i++) {
6872 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6873 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006874 sp<AudioPolicyMix> primaryMix;
6875 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006876 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006877 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6878 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
6879 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006880 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6881 for (auto &secondaryMix : secondaryMixes) {
6882 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6883 if (outputDesc != nullptr &&
6884 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6885 secondaryDescs.push_back(outputDesc);
6886 }
6887 }
6888
jiabinc44b3462022-12-08 12:52:31 -08006889 if (status != OK &&
6890 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
6891 // When it failed to query secondary output, only invalidate the client that is not
6892 // MMAP. The reason is that MMAP stream will not support secondary output.
6893 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00006894 } else if (!std::equal(
6895 client->getSecondaryOutputs().begin(),
6896 client->getSecondaryOutputs().end(),
6897 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006898 if (!audio_is_linear_pcm(client->config().format)) {
6899 // If the format is not PCM, the tracks should be invalidated to get correct
6900 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08006901 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00006902 } else {
6903 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6904 std::vector<audio_io_handle_t> secondaryOutputIds;
6905 for (const auto &secondaryDesc: secondaryDescs) {
6906 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6907 weakSecondaryDescs.push_back(secondaryDesc);
6908 }
6909 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6910 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006911 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006912 }
6913 }
6914 }
jiabin10a03f12021-05-07 23:46:28 +00006915 if (!trackSecondaryOutputs.empty()) {
6916 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6917 }
jiabinc44b3462022-12-08 12:52:31 -08006918 if (!clientsToInvalidate.empty()) {
6919 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
6920 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006921 }
6922}
6923
Eric Laurent2517af32020-11-25 15:31:27 +01006924bool AudioPolicyManager::isScoRequestedForComm() const {
6925 AudioDeviceTypeAddrVector devices;
6926 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6927 for (const auto &device : devices) {
6928 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6929 return true;
6930 }
6931 }
6932 return false;
6933}
6934
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006935bool AudioPolicyManager::isHearingAidUsedForComm() const {
6936 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6937 true /*fromCache*/);
6938 for (const auto &device : devices) {
6939 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6940 return true;
6941 }
6942 }
6943 return false;
6944}
6945
6946
Eric Laurente0720872014-03-11 09:30:41 -07006947void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006948{
François Gaffie53615e22015-03-19 09:24:12 +01006949 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006950 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006951 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006952 return;
6953 }
6954
Eric Laurent3a4311c2014-03-17 12:00:47 -07006955 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006956 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6957 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006958 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006959
6960 // if suspended, restore A2DP output if:
6961 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006962 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006963 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006964 //
Eric Laurentf732e072016-08-03 19:30:28 -07006965 // if not suspended, suspend A2DP output if:
6966 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006967 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006968 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006969 //
6970 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006971 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006972 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006973 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006974 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006975
6976 mpClientInterface->restoreOutput(a2dpOutput);
6977 mA2dpSuspended = false;
6978 }
6979 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006980 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006981 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006982 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006983 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006984
6985 mpClientInterface->suspendOutput(a2dpOutput);
6986 mA2dpSuspended = true;
6987 }
6988 }
6989}
6990
François Gaffie11d30102018-11-02 16:09:09 +01006991DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6992 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006993{
François Gaffie11d30102018-11-02 16:09:09 +01006994 DeviceVector devices;
6995
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006996 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006997 if (index >= 0) {
6998 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006999 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007000 ALOGV("%s device %s forced by patch %d", __func__,
7001 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7002 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007003 }
7004 }
7005
Dean Wheatley514b4312020-06-17 21:45:00 +10007006 // Do not retrieve engine device for outputs through MSD
7007 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7008 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7009 return outputDesc->devices();
7010 }
7011
Eric Laurent97ac8712018-07-27 18:59:02 -07007012 // Honor explicit routing requests only if no client using default routing is active on this
7013 // input: a specific app can not force routing for other apps by setting a preferred device.
7014 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007015 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007016 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007017 if (device != nullptr) {
7018 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007019 }
7020
François Gaffiea807ef92018-11-05 10:44:33 +01007021 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7022 // of setForceUse / Default Bus device here
7023 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7024 if (device != nullptr) {
7025 return DeviceVector(device);
7026 }
7027
François Gaffiec005e562018-11-06 15:04:49 +01007028 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7029 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7030 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307031 auto hasStreamActive = [&](auto stream) {
7032 return hasStream(streams, stream) && isStreamActive(stream, 0);
7033 };
Eric Laurent484e9272018-06-07 17:29:23 -07007034
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307035 auto doGetOutputDevicesForVoice = [&]() {
7036 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007037 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307038 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007039 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7040 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307041 };
7042
7043 // With low-latency playing on speaker, music on WFD, when the first low-latency
7044 // output is stopped, getNewOutputDevices checks for a product strategy
7045 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007046 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307047 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7048 // stream is associated to the output descriptor.
7049 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7050 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7051 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7052 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007053 // Retrieval of devices for voice DL is done on primary output profile, cannot
7054 // check the route (would force modifying configuration file for this profile)
7055 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7056 break;
7057 }
Eric Laurente552edb2014-03-10 17:42:56 -07007058 }
François Gaffiec005e562018-11-06 15:04:49 +01007059 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007060 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007061}
7062
François Gaffie11d30102018-11-02 16:09:09 +01007063sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7064 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007065{
François Gaffie11d30102018-11-02 16:09:09 +01007066 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007067
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007068 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007069 if (index >= 0) {
7070 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007071 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007072 ALOGV("getNewInputDevice() device %s forced by patch %d",
7073 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7074 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007075 }
7076 }
7077
Eric Laurent97ac8712018-07-27 18:59:02 -07007078 // Honor explicit routing requests only if no client using default routing is active on this
7079 // input: a specific app can not force routing for other apps by setting a preferred device.
7080 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007081 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7082 if (device != nullptr) {
7083 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007084 }
7085
Eric Laurentdc95a252018-04-12 12:46:56 -07007086 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007087 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007088 audio_attributes_t attributes;
7089 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007090 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007091 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7092 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007093 attributes = topClient->attributes();
7094 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007095 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007096 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007097 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7098 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007099 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007100 }
7101
Francois Gaffie716e1432019-01-14 16:58:59 +01007102 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7103 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007104 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007105 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007106 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007107 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007108
Eric Laurente552edb2014-03-10 17:42:56 -07007109 return device;
7110}
7111
Eric Laurent794fde22016-03-11 09:50:45 -08007112bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7113 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007114 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007115}
7116
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007117status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007118 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007119 if (devices == nullptr) {
7120 return BAD_VALUE;
7121 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007122
Andy Hung6d23c0f2022-02-16 09:37:15 -08007123 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007124 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7125 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007126 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007127 for (const auto& device : curDevices) {
7128 devices->push_back(device->getDeviceTypeAddr());
7129 }
7130 return NO_ERROR;
7131}
7132
Eric Laurente0720872014-03-11 09:30:41 -07007133void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007134 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007135 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007136 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007137 updateDevicesAndOutputs();
7138 break;
7139 default:
7140 break;
7141 }
7142}
7143
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007144uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007145
7146 // skip beacon mute management if a dedicated TTS output is available
7147 if (mTtsOutputAvailable) {
7148 return 0;
7149 }
7150
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007151 switch(event) {
7152 case STARTING_OUTPUT:
7153 mBeaconMuteRefCount++;
7154 break;
7155 case STOPPING_OUTPUT:
7156 if (mBeaconMuteRefCount > 0) {
7157 mBeaconMuteRefCount--;
7158 }
7159 break;
7160 case STARTING_BEACON:
7161 mBeaconPlayingRefCount++;
7162 break;
7163 case STOPPING_BEACON:
7164 if (mBeaconPlayingRefCount > 0) {
7165 mBeaconPlayingRefCount--;
7166 }
7167 break;
7168 }
7169
7170 if (mBeaconMuteRefCount > 0) {
7171 // any playback causes beacon to be muted
7172 return setBeaconMute(true);
7173 } else {
7174 // no other playback: unmute when beacon starts playing, mute when it stops
7175 return setBeaconMute(mBeaconPlayingRefCount == 0);
7176 }
7177}
7178
7179uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7180 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7181 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7182 // keep track of muted state to avoid repeating mute/unmute operations
7183 if (mBeaconMuted != mute) {
7184 // mute/unmute AUDIO_STREAM_TTS on all outputs
7185 ALOGV("\t muting %d", mute);
7186 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007187 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7188 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7189 ALOGV("\t no tts volume source available");
7190 return 0;
7191 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007192 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007193 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007194 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007195 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007196 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007197 maxLatency = latency;
7198 }
7199 }
7200 mBeaconMuted = mute;
7201 return maxLatency;
7202 }
7203 return 0;
7204}
7205
Eric Laurente0720872014-03-11 09:30:41 -07007206void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007207{
François Gaffiec005e562018-11-06 15:04:49 +01007208 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007209 mPreviousOutputs = mOutputs;
7210}
7211
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007212uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007213 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007214 uint32_t delayMs)
7215{
7216 // mute/unmute strategies using an incompatible device combination
7217 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7218 // if unmuting, unmute only after the specified delay
7219 if (outputDesc->isDuplicated()) {
7220 return 0;
7221 }
7222
7223 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007224 DeviceVector devices = outputDesc->devices();
7225 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007226
François Gaffiec005e562018-11-06 15:04:49 +01007227 auto productStrategies = mEngine->getOrderedProductStrategies();
7228 for (const auto &productStrategy : productStrategies) {
7229 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7230 DeviceVector curDevices =
7231 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7232 curDevices = curDevices.filter(outputDesc->supportedDevices());
7233 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007234 bool doMute = false;
7235
François Gaffiec005e562018-11-06 15:04:49 +01007236 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007237 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007238 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7239 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007240 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007241 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007242 }
Eric Laurent99401132014-05-07 19:48:15 -07007243 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007244 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007245 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007246 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007247 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007248 continue;
7249 }
François Gaffiec005e562018-11-06 15:04:49 +01007250 ALOGVV("%s() %s (curDevice %s)", __func__,
7251 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7252 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7253 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007254 if (mute) {
7255 // FIXME: should not need to double latency if volume could be applied
7256 // immediately by the audioflinger mixer. We must account for the delay
7257 // between now and the next time the audioflinger thread for this output
7258 // will process a buffer (which corresponds to one buffer size,
7259 // usually 1/2 or 1/4 of the latency).
7260 if (muteWaitMs < desc->latency() * 2) {
7261 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007262 }
7263 }
7264 }
7265 }
7266 }
7267 }
7268
Eric Laurent99401132014-05-07 19:48:15 -07007269 // temporary mute output if device selection changes to avoid volume bursts due to
7270 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007271 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007272 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007273
Eric Laurentdc462862016-07-19 12:29:53 -07007274 if (muteWaitMs < tempMuteWaitMs) {
7275 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007276 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007277
7278 // If recommended duration is defined, replace temporary mute duration to avoid
7279 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7280 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7281 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7282 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7283 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7284
François Gaffieaaac0fd2018-11-22 17:56:39 +01007285 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7286 // make sure that we do not start the temporary mute period too early in case of
7287 // delayed device change
7288 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7289 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007290 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007291 }
7292 }
7293
Eric Laurente552edb2014-03-10 17:42:56 -07007294 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7295 if (muteWaitMs > delayMs) {
7296 muteWaitMs -= delayMs;
7297 usleep(muteWaitMs * 1000);
7298 return muteWaitMs;
7299 }
7300 return 0;
7301}
7302
François Gaffie11d30102018-11-02 16:09:09 +01007303uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7304 const DeviceVector &devices,
7305 bool force,
7306 int delayMs,
7307 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02007308 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07007309{
jiabin3ff8d7d2022-12-13 06:27:44 +00007310 // TODO(b/262404095): Consider if the output need to be reopened.
François Gaffie11d30102018-11-02 16:09:09 +01007311 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007312 uint32_t muteWaitMs;
7313
7314 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01007315 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
7316 nullptr /* patchHandle */, requiresMuteCheck);
7317 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
7318 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07007319 return muteWaitMs;
7320 }
Eric Laurente552edb2014-03-10 17:42:56 -07007321
7322 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007323 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007324 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007325 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007326
François Gaffie11d30102018-11-02 16:09:09 +01007327 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7328
7329 if (!filteredDevices.isEmpty()) {
7330 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007331 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007332
7333 // if the outputs are not materially active, there is no need to mute.
7334 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007335 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007336 } else {
7337 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7338 muteWaitMs = 0;
7339 }
Eric Laurente552edb2014-03-10 17:42:56 -07007340
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007341 bool outputRouted = outputDesc->isRouted();
7342
Eric Laurent79ea9582020-06-11 18:49:24 -07007343 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7344 // output profile or if new device is not supported AND previous device(s) is(are) still
7345 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007346 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007347 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7348 // restore previous device after evaluating strategy mute state
7349 outputDesc->setDevices(prevDevices);
7350 return muteWaitMs;
7351 }
7352
Eric Laurente552edb2014-03-10 17:42:56 -07007353 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007354 // the requested device is AUDIO_DEVICE_NONE
7355 // OR the requested device is the same as current device
7356 // AND force is not specified
7357 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007358 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007359 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007360 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7361 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007362 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7363 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7364 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7365 }
Eric Laurente552edb2014-03-10 17:42:56 -07007366 return muteWaitMs;
7367 }
7368
François Gaffie11d30102018-11-02 16:09:09 +01007369 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007370
Eric Laurente552edb2014-03-10 17:42:56 -07007371 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007372 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007373 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007374 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007375 PatchBuilder patchBuilder;
7376 patchBuilder.addSource(outputDesc);
7377 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7378 for (const auto &filteredDevice : filteredDevices) {
7379 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007380 }
7381
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007382 // Add half reported latency to delayMs when muteWaitMs is null in order
7383 // to avoid disordered sequence of muting volume and changing devices.
7384 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7385 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007386 }
Eric Laurente552edb2014-03-10 17:42:56 -07007387
7388 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007389 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007390
7391 return muteWaitMs;
7392}
7393
Eric Laurentc75307b2015-03-17 15:29:32 -07007394status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007395 int delayMs,
7396 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007397{
Eric Laurent6a94d692014-05-20 11:18:06 -07007398 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007399 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7400 return INVALID_OPERATION;
7401 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007402 if (patchHandle) {
7403 index = mAudioPatches.indexOfKey(*patchHandle);
7404 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007405 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007406 }
7407 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007408 return INVALID_OPERATION;
7409 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007410 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007411 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007412 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007413 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007414 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007415 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007416 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007417 return status;
7418}
7419
7420status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007421 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007422 bool force,
7423 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007424{
7425 status_t status = NO_ERROR;
7426
Eric Laurent1f2f2232014-06-02 12:01:23 -07007427 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007428 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7429 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007430
François Gaffie11d30102018-11-02 16:09:09 +01007431 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007432 PatchBuilder patchBuilder;
7433 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007434 // AUDIO_SOURCE_HOTWORD is for internal use only:
7435 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007436 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7437 auto result = usecase;
7438 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7439 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7440 }
7441 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007442 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007443 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007444 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007445 }
7446 }
7447 return status;
7448}
7449
Eric Laurent6a94d692014-05-20 11:18:06 -07007450status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7451 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007452{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007453 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007454 ssize_t index;
7455 if (patchHandle) {
7456 index = mAudioPatches.indexOfKey(*patchHandle);
7457 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007458 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007459 }
7460 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007461 return INVALID_OPERATION;
7462 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007463 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007464 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007465 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007466 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007467 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007468 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007469 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007470 return status;
7471}
7472
François Gaffie11d30102018-11-02 16:09:09 +01007473sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007474 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007475 audio_format_t& format,
7476 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007477 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007478{
7479 // Choose an input profile based on the requested capture parameters: select the first available
7480 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007481 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007482 //
7483 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7484 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007485
Atneya Nair0f0a8032022-12-12 16:20:12 -08007486 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7487 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7488 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7489
7490 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007491
jiabin2fd710d2022-05-02 23:20:22 +00007492 for (;;) {
7493 sp<IOProfile> firstInexact = nullptr;
7494 uint32_t updatedSamplingRate = 0;
7495 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7496 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7497 for (const auto& hwModule : mHwModules) {
7498 for (const auto& profile : hwModule->getInputProfiles()) {
7499 // profile->log();
7500 //updatedFormat = format;
7501 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7502 &samplingRate /*updatedSamplingRate*/,
7503 format,
7504 &format, /*updatedFormat*/
7505 channelMask,
7506 &channelMask /*updatedChannelMask*/,
7507 // FIXME ugly cast
7508 (audio_output_flags_t) flags,
7509 true /*exactMatchRequiredForInputFlags*/)) {
7510 return profile;
7511 }
7512 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7513 samplingRate,
7514 &updatedSamplingRate,
7515 format,
7516 &updatedFormat,
7517 channelMask,
7518 &updatedChannelMask,
7519 // FIXME ugly cast
7520 (audio_output_flags_t) flags,
7521 false /*exactMatchRequiredForInputFlags*/)) {
7522 firstInexact = profile;
7523 }
7524 }
7525 }
7526
7527 if (firstInexact != nullptr) {
7528 samplingRate = updatedSamplingRate;
7529 format = updatedFormat;
7530 channelMask = updatedChannelMask;
7531 return firstInexact;
7532 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7533 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7534 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7535 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7536 flags = AUDIO_INPUT_FLAG_NONE;
7537 } else { // fail
7538 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7539 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7540 samplingRate, format, channelMask, oriFlags);
7541 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007542 }
7543 }
jiabin2fd710d2022-05-02 23:20:22 +00007544
7545 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007546}
7547
François Gaffieaaac0fd2018-11-22 17:56:39 +01007548float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7549 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007550 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007551 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007552{
jiabin9a3361e2019-10-01 09:38:30 -07007553 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007554
7555 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7556 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7557 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7558 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007559 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7560 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7561 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7562 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7563 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007564
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007565 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007566 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7567 mOutputs.isActive(ringVolumeSrc, 0)) {
7568 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007569 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007570 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007571 }
7572
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007573 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007574 if ((volumeSource != callVolumeSrc && (isInCall() ||
7575 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007576 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007577 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7578 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007579 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7580 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7581 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007582 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007583 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007584 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007585 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007586 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007587 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007588 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7589 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7590 // programmatically muted.
7591 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7592 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7593 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007594 bool exemptFromCapping =
7595 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7596 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007597 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7598 volumeSource, volumeDb);
7599 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007600 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7601 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7602 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007603 }
7604 }
Eric Laurente552edb2014-03-10 17:42:56 -07007605 // if a headset is connected, apply the following rules to ring tones and notifications
7606 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007607 // - always attenuate notifications volume by 6dB
7608 // - attenuate ring tones volume by 6dB unless music is not playing and
7609 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007610 // - if music is playing, always limit the volume to current music volume,
7611 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007612 if (!Intersection(deviceTypes,
7613 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7614 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007615 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7616 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007617 ((volumeSource == alarmVolumeSrc ||
7618 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007619 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7620 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7621 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007622 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7623 curves.canBeMuted()) {
7624
Eric Laurente552edb2014-03-10 17:42:56 -07007625 // when the phone is ringing we must consider that music could have been paused just before
7626 // by the music application and behave as if music was active if the last music track was
7627 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007628 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007629 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007630 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007631 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007632 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7633 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007634 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007635 float musicVolDb = computeVolume(musicCurves,
7636 musicVolumeSrc,
7637 musicCurves.getVolumeIndex(musicDevice),
7638 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007639 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7640 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7641 if (volumeDb > minVolDb) {
7642 volumeDb = minVolDb;
7643 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007644 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007645 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7646 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7647 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007648 // on A2DP, also ensure notification volume is not too low compared to media when
7649 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007650 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007651 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007652 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7653 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007654 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7655 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007656 }
7657 }
jiabin9a3361e2019-10-01 09:38:30 -07007658 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007659 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007660 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007661 }
7662 }
7663
François Gaffie43c73442018-11-08 08:21:55 +01007664 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007665}
7666
Eric Laurent3839bc02018-07-10 18:33:34 -07007667int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007668 VolumeSource fromVolumeSource,
7669 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007670{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007671 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007672 return srcIndex;
7673 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007674 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7675 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007676 float minSrc = (float)srcCurves.getVolumeIndexMin();
7677 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7678 float minDst = (float)dstCurves.getVolumeIndexMin();
7679 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007680
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007681 // preserve mute request or correct range
7682 if (srcIndex < minSrc) {
7683 if (srcIndex == 0) {
7684 return 0;
7685 }
7686 srcIndex = minSrc;
7687 } else if (srcIndex > maxSrc) {
7688 srcIndex = maxSrc;
7689 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007690 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7691}
7692
François Gaffieaaac0fd2018-11-22 17:56:39 +01007693status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7694 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007695 int index,
7696 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007697 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007698 int delayMs,
7699 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007700{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007701 // do not change actual attributes volume if the attributes is muted
7702 if (outputDesc->isMuted(volumeSource)) {
7703 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7704 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007705 return NO_ERROR;
7706 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007707 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7708 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7709 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7710 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007711
Eric Laurent2517af32020-11-25 15:31:27 +01007712 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007713 bool isHAUsed = isHearingAidUsedForComm();
7714
Eric Laurente552edb2014-03-10 17:42:56 -07007715 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007716 // if sco and call follow same curves, bypass forceUseForComm
7717 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007718 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007719 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7720 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007721 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007722 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007723 // Do not return an error here as AudioService will always set both voice call
7724 // and bluetooth SCO volumes due to stream aliasing.
7725 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007726 }
jiabin9a3361e2019-10-01 09:38:30 -07007727 if (deviceTypes.empty()) {
7728 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007729 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007730
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007731 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7732 ALOGE("invalid volume index range");
7733 return BAD_VALUE;
7734 }
7735
jiabin9a3361e2019-10-01 09:38:30 -07007736 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7737 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007738 // Force VoIP volume to max for bluetooth SCO device except if muted
7739 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007740 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007741 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007742 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007743 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007744 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007745 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007746
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007747 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007748 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007749 // 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 +01007750 if (isVoiceVolSrc) {
7751 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007752 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007753 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007754 }
Eric Laurent18fba842016-03-31 14:41:26 -07007755 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007756 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7757 mLastVoiceVolume = voiceVolume;
7758 }
7759 }
Eric Laurente552edb2014-03-10 17:42:56 -07007760 return NO_ERROR;
7761}
7762
Eric Laurentc75307b2015-03-17 15:29:32 -07007763void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007764 const DeviceTypeSet& deviceTypes,
7765 int delayMs,
7766 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007767{
jiabincd510522020-01-22 09:40:55 -08007768 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007769 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7770 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7771 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007772 curves.getVolumeIndex(deviceTypes),
7773 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007774 }
7775}
7776
François Gaffiec005e562018-11-06 15:04:49 +01007777void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7778 bool on,
7779 const sp<AudioOutputDescriptor>& outputDesc,
7780 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007781 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007782{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007783 std::vector<VolumeSource> sourcesToMute;
7784 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7785 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7786 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007787 VolumeSource source = toVolumeSource(attributes, false);
7788 if ((source != VOLUME_SOURCE_NONE) &&
7789 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7790 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007791 sourcesToMute.push_back(source);
7792 }
Eric Laurente552edb2014-03-10 17:42:56 -07007793 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007794 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007795 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007796 }
7797
Eric Laurente552edb2014-03-10 17:42:56 -07007798}
7799
François Gaffieaaac0fd2018-11-22 17:56:39 +01007800void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7801 bool on,
7802 const sp<AudioOutputDescriptor>& outputDesc,
7803 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007804 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007805{
jiabin9a3361e2019-10-01 09:38:30 -07007806 if (deviceTypes.empty()) {
7807 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007808 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007809 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007810 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007811 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007812 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007813 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007814 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7815 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007816 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007817 }
7818 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007819 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7820 // ignored
7821 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007822 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007823 if (!outputDesc->isMuted(volumeSource)) {
7824 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007825 return;
7826 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007827 if (outputDesc->decMuteCount(volumeSource) == 0) {
7828 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007829 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007830 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007831 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007832 delayMs);
7833 }
7834 }
7835}
7836
François Gaffie53615e22015-03-19 09:24:12 +01007837bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7838{
François Gaffiec005e562018-11-06 15:04:49 +01007839 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007840 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7841 return true;
7842 }
7843
7844 // has known usage?
7845 switch (paa->usage) {
7846 case AUDIO_USAGE_UNKNOWN:
7847 case AUDIO_USAGE_MEDIA:
7848 case AUDIO_USAGE_VOICE_COMMUNICATION:
7849 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7850 case AUDIO_USAGE_ALARM:
7851 case AUDIO_USAGE_NOTIFICATION:
7852 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7853 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7854 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7855 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7856 case AUDIO_USAGE_NOTIFICATION_EVENT:
7857 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7858 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7859 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7860 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007861 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007862 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007863 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007864 case AUDIO_USAGE_EMERGENCY:
7865 case AUDIO_USAGE_SAFETY:
7866 case AUDIO_USAGE_VEHICLE_STATUS:
7867 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007868 break;
7869 default:
7870 return false;
7871 }
7872 return true;
7873}
7874
François Gaffie2110e042015-03-24 08:41:51 +01007875audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7876{
7877 return mEngine->getForceUse(usage);
7878}
7879
Eric Laurent96d1dda2022-03-14 17:14:19 +01007880bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007881 return isStateInCall(mEngine->getPhoneState());
7882}
7883
Eric Laurent96d1dda2022-03-14 17:14:19 +01007884bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007885 return is_state_in_call(state);
7886}
7887
Eric Laurentf9cccec2022-11-16 19:12:00 +01007888bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007889 audio_mode_t mode = mEngine->getPhoneState();
7890 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007891 || (mode == AUDIO_MODE_CALL_SCREEN)
7892 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007893}
7894
Eric Laurentf9cccec2022-11-16 19:12:00 +01007895bool AudioPolicyManager::isInCallOrScreening() const {
7896 audio_mode_t mode = mEngine->getPhoneState();
7897 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7898}
7899
Eric Laurentd60560a2015-04-10 11:31:20 -07007900void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7901{
7902 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007903 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007904 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007905 sourceDesc->sinkDevice()->equals(deviceDesc))
7906 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007907 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007908 }
7909 }
7910
7911 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7912 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7913 bool release = false;
7914 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7915 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7916 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7917 source->ext.device.type == deviceDesc->type()) {
7918 release = true;
7919 }
7920 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007921 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007922 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7923 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7924 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007925 sink->ext.device.type == deviceDesc->type() &&
7926 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7927 || strncmp(sink->ext.device.address, address,
7928 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007929 release = true;
7930 }
7931 }
7932 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007933 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7934 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007935 }
7936 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007937
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007938 mInputs.clearSessionRoutesForDevice(deviceDesc);
7939
Francois Gaffie716e1432019-01-14 16:58:59 +01007940 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007941}
7942
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007943void AudioPolicyManager::modifySurroundFormats(
7944 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007945 std::unordered_set<audio_format_t> enforcedSurround(
7946 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007947 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7948 for (const auto& pair : mConfig.getSurroundFormats()) {
7949 allSurround.insert(pair.first);
7950 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7951 }
Phil Burk09bc4612016-02-24 15:58:15 -08007952
7953 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7954 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007955 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007956 // This is the resulting set of formats depending on the surround mode:
7957 // 'all surround' = allSurround
7958 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7959 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7960 // 'manual surround' = mManualSurroundFormats
7961 // AUTO: formats v 'enforced surround'
7962 // ALWAYS: formats v 'all surround' v 'enforced surround'
7963 // NEVER: formats ^ 'non-surround'
7964 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007965
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007966 std::unordered_set<audio_format_t> formatSet;
7967 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7968 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007969 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007970 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007971 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007972 formatSet.insert(*formatIter);
7973 }
7974 }
7975 } else {
7976 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7977 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007978 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007979
jiabin81772902018-04-02 17:52:27 -07007980 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007981 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007982 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7983 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7984 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007985 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007986 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7987 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7988 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007989 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007990 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007991 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007992 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007993 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007994 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007995}
7996
jiabin06e4bab2019-07-29 10:13:34 -07007997void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7998 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007999 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8000 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8001
8002 // If NEVER, then remove support for channelMasks > stereo.
8003 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008004 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8005 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008006 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008007 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008008 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008009 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008010 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008011 }
8012 }
jiabin81772902018-04-02 17:52:27 -07008013 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8014 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8015 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008016 bool supports5dot1 = false;
8017 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008018 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008019 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8020 supports5dot1 = true;
8021 break;
8022 }
8023 }
8024 // If not then add 5.1 support.
8025 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008026 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008027 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008028 }
Phil Burk09bc4612016-02-24 15:58:15 -08008029 }
8030}
8031
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008032void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008033 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01008034 AudioProfileVector &profiles)
8035{
8036 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008037 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07008038
François Gaffie112b0af2015-11-19 16:13:25 +01008039 // Format MUST be checked first to update the list of AudioProfile
8040 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008041 reply = mpClientInterface->getParameters(
8042 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07008043 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008044 AudioParameter repliedParameters(reply);
8045 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008046 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01008047 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
8048 return;
8049 }
Phil Burk09bc4612016-02-24 15:58:15 -08008050 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01008051 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08008052 if (device == AUDIO_DEVICE_OUT_HDMI
8053 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008054 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07008055 }
jiabin3e277cc2019-09-10 14:27:34 -07008056 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01008057 }
François Gaffie112b0af2015-11-19 16:13:25 +01008058
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008059 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07008060 ChannelMaskSet channelMasks;
8061 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01008062 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07008063 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01008064
8065 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008066 reply = mpClientInterface->getParameters(
8067 ioHandle,
8068 requestedParameters.toString() + ";" +
8069 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01008070 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008071 AudioParameter repliedParameters(reply);
8072 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008073 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008074 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01008075 }
8076 }
8077 if (profiles.hasDynamicChannelsFor(format)) {
8078 reply = mpClientInterface->getParameters(ioHandle,
8079 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07008080 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01008081 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008082 AudioParameter repliedParameters(reply);
8083 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008084 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008085 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008086 if (device == AUDIO_DEVICE_OUT_HDMI
8087 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008088 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07008089 }
François Gaffie112b0af2015-11-19 16:13:25 +01008090 }
8091 }
jiabin3e277cc2019-09-10 14:27:34 -07008092 addDynamicAudioProfileAndSort(
8093 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01008094 }
8095}
Eric Laurentd60560a2015-04-10 11:31:20 -07008096
Mikhail Naganovdc769682018-05-04 15:34:08 -07008097status_t AudioPolicyManager::installPatch(const char *caller,
8098 audio_patch_handle_t *patchHandle,
8099 AudioIODescriptorInterface *ioDescriptor,
8100 const struct audio_patch *patch,
8101 int delayMs)
8102{
8103 ssize_t index = mAudioPatches.indexOfKey(
8104 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8105 *patchHandle : ioDescriptor->getPatchHandle());
8106 sp<AudioPatch> patchDesc;
8107 status_t status = installPatch(
8108 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8109 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008110 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008111 }
8112 return status;
8113}
8114
8115status_t AudioPolicyManager::installPatch(const char *caller,
8116 ssize_t index,
8117 audio_patch_handle_t *patchHandle,
8118 const struct audio_patch *patch,
8119 int delayMs,
8120 uid_t uid,
8121 sp<AudioPatch> *patchDescPtr)
8122{
8123 sp<AudioPatch> patchDesc;
8124 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8125 if (index >= 0) {
8126 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008127 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008128 }
8129
8130 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8131 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8132 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8133 if (status == NO_ERROR) {
8134 if (index < 0) {
8135 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008136 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008137 } else {
8138 patchDesc->mPatch = *patch;
8139 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008140 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008141 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008142 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008143 }
8144 nextAudioPortGeneration();
8145 mpClientInterface->onAudioPatchListUpdate();
8146 }
8147 if (patchDescPtr) *patchDescPtr = patchDesc;
8148 return status;
8149}
8150
jiabinbce0c1d2020-10-05 11:20:18 -07008151bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8152{
8153 const TrackClientVector activeClients = output->getActiveClients();
8154 if (activeClients.empty()) {
8155 return true;
8156 }
8157 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8158 if (index < 0) {
8159 ALOGE("%s, no audio patch found while there are active clients on output %d",
8160 __func__, output->getId());
8161 return false;
8162 }
8163 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8164 DeviceVector routedDevices;
8165 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8166 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8167 patchDesc->mPatch.sinks[i].id);
8168 if (device == nullptr) {
8169 ALOGE("%s, no audio device found with id(%d)",
8170 __func__, patchDesc->mPatch.sinks[i].id);
8171 return false;
8172 }
8173 routedDevices.add(device);
8174 }
8175 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008176 if (client->isInvalid()) {
8177 // No need to take care about invalidated clients.
8178 continue;
8179 }
jiabinbce0c1d2020-10-05 11:20:18 -07008180 sp<DeviceDescriptor> preferredDevice =
8181 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8182 if (mEngine->getOutputDevicesForAttributes(
8183 client->attributes(), preferredDevice, false) == routedDevices) {
8184 return false;
8185 }
8186 }
8187 return true;
8188}
8189
8190sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008191 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008192 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8193 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008194{
8195 for (const auto& device : devices) {
8196 // TODO: This should be checking if the profile supports the device combo.
8197 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008198 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8199 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008200 return nullptr;
8201 }
8202 }
8203 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8204 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008205 status_t status = desc->open(halConfig, mixerConfig, devices,
8206 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008207 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008208 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008209 return nullptr;
8210 }
8211
8212 // Here is where the out_set_parameters() for card & device gets called
8213 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8214 const audio_devices_t deviceType = device->type();
8215 const String8 &address = String8(device->address().c_str());
8216 if (!address.isEmpty()) {
8217 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8218 mpClientInterface->setParameters(output, String8(param));
8219 free(param);
8220 }
8221 updateAudioProfiles(device, output, profile->getAudioProfiles());
8222 if (!profile->hasValidAudioProfile()) {
8223 ALOGW("%s() missing param", __func__);
8224 desc->close();
8225 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008226 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8227 // Reopen the output with the best audio profile picked by APM when the profile supports
8228 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008229 desc->close();
8230 output = AUDIO_IO_HANDLE_NONE;
8231 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8232 profile->pickAudioProfile(
8233 config.sample_rate, config.channel_mask, config.format);
8234 config.offload_info.sample_rate = config.sample_rate;
8235 config.offload_info.channel_mask = config.channel_mask;
8236 config.offload_info.format = config.format;
8237
jiabina84c3d32022-12-02 18:59:55 +00008238 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008239 if (status != NO_ERROR) {
8240 return nullptr;
8241 }
8242 }
8243
8244 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008245
baek.kim -61c20122022-07-27 10:05:32 +00008246 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8247 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8248
jiabinbce0c1d2020-10-05 11:20:18 -07008249 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8250 sp<AudioPolicyMix> policyMix;
8251 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8252 policyMix->setOutput(desc);
8253 desc->mPolicyMix = policyMix;
8254 } else {
8255 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
8256 address.string());
8257 }
8258
baek.kim -61c20122022-07-27 10:05:32 +00008259 } else if (hasPrimaryOutput() && speaker != nullptr
8260 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008261 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8262 // no duplicated output for:
8263 // - direct outputs
8264 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008265 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008266 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8267
8268 //TODO: configure audio effect output stage here
8269
8270 // open a duplicating output thread for the new output and the primary output
8271 sp<SwAudioOutputDescriptor> dupOutputDesc =
8272 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8273 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8274 if (status == NO_ERROR) {
8275 // add duplicated output descriptor
8276 addOutput(duplicatedOutput, dupOutputDesc);
8277 } else {
8278 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8279 mPrimaryOutput->mIoHandle, output);
8280 desc->close();
8281 removeOutput(output);
8282 nextAudioPortGeneration();
8283 return nullptr;
8284 }
8285 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008286 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8287 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8288 mPrimaryOutput = desc;
8289 }
jiabinbce0c1d2020-10-05 11:20:18 -07008290 return desc;
8291}
8292
jiabinf1c73972022-04-14 16:28:52 -07008293status_t AudioPolicyManager::getDevicesForAttributes(
8294 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8295 // Devices are determined in the following precedence:
8296 //
8297 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8298 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8299 //
8300 // If no such dynamic policy then
8301 // 2) Devices containing an active client using setPreferredDevice
8302 // with same strategy as the attributes.
8303 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8304 //
8305 // If no corresponding active client with setPreferredDevice then
8306 // 3) Devices associated with the strategy determined by the attributes
8307 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8308 //
8309 // See related getOutputForAttrInt().
8310
8311 // check dynamic policies but only for primary descriptors (secondary not used for audible
8312 // audio routing, only used for duplication for playback capture)
8313 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008314 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008315 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008316 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8317 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8318 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008319 if (status != OK) {
8320 return status;
8321 }
8322
8323 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8324 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8325 // as they are unaffected by device/stream volume
8326 // (per SwAudioOutputDescriptor::isFixedVolume()).
8327 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8328 ) {
8329 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8330 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8331 devices.add(deviceDesc);
8332 } else {
8333 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8334 // which selects setPreferredDevice if active. This means forVolume call
8335 // will take an active setPreferredDevice, if such exists.
8336
8337 devices = mEngine->getOutputDevicesForAttributes(
8338 attr, nullptr /* preferredDevice */, false /* fromCache */);
8339 }
8340
8341 if (forVolume) {
8342 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8343 // for single volume control in AudioService (such relationship should exist if
8344 // SPEAKER_SAFE is present).
8345 //
8346 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8347 DeviceVector speakerSafeDevices =
8348 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8349 if (!speakerSafeDevices.isEmpty()) {
8350 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8351 devices.remove(speakerSafeDevices);
8352 }
8353 }
8354
8355 return NO_ERROR;
8356}
8357
8358status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8359 AudioProfileVector& audioProfiles,
8360 uint32_t flags,
8361 bool isInput) {
8362 for (const auto& hwModule : mHwModules) {
8363 // the MSD module checks for different conditions
8364 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8365 continue;
8366 }
8367 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8368 : hwModule->getOutputProfiles();
8369 for (const auto& profile : ioProfiles) {
8370 if (!profile->areAllDevicesSupported(devices) ||
8371 !profile->isCompatibleProfileForFlags(
8372 flags, false /*exactMatchRequiredForInputFlags*/)) {
8373 continue;
8374 }
8375 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8376 }
8377 }
8378
8379 if (!isInput) {
8380 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8381 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8382 if (msdModule != nullptr) {
8383 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8384 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8385 for (const auto &profile: msdModule->getOutputProfiles()) {
8386 if (!profile->asAudioPort()->isDirectOutput()) {
8387 continue;
8388 }
8389 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8390 }
8391 } else {
8392 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8393 }
8394 }
8395 }
8396
8397 return NO_ERROR;
8398}
8399
jiabin3ff8d7d2022-12-13 06:27:44 +00008400sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8401 const audio_config_t *config,
8402 audio_output_flags_t flags,
8403 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008404 closeOutput(outputDesc->mIoHandle);
8405 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8406 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8407 if (preferredOutput == nullptr) {
8408 ALOGE("%s failed to reopen output device=%d, caller=%s",
8409 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008410 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008411 return preferredOutput;
8412}
8413
8414void AudioPolicyManager::reopenOutputsWithDevices(
8415 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8416 for (const auto& [output, devices] : outputsToReopen) {
8417 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8418 closeOutput(output);
8419 openOutputWithProfileAndDevice(desc->mProfile, devices);
8420 }
jiabina84c3d32022-12-02 18:59:55 +00008421}
8422
jiabinc44b3462022-12-08 12:52:31 -08008423PortHandleVector AudioPolicyManager::getClientsForStream(
8424 audio_stream_type_t streamType) const {
8425 PortHandleVector clients;
8426 for (size_t i = 0; i < mOutputs.size(); ++i) {
8427 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8428 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8429 }
8430 return clients;
8431}
8432
8433void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8434 PortHandleVector clients;
8435 for (auto stream : streams) {
8436 PortHandleVector clientsForStream = getClientsForStream(stream);
8437 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8438 }
8439 mpClientInterface->invalidateTracks(clients);
8440}
8441
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008442} // namespace android