blob: bdb5463c93f7430bb6ea0edaa0b46733aca64442 [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 }
1585
Eric Laurente552edb2014-03-10 17:42:56 -07001586 // ignoring channel mask due to downmix capability in mixer
1587
1588 // open a non direct output
1589
1590 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001591 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001592 // get which output is suitable for the specified stream. The actual
1593 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001594 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001595 if (prefMixerConfigInfo != nullptr) {
1596 for (audio_io_handle_t outputHandle : outputs) {
1597 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1598 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1599 output = outputHandle;
1600 break;
1601 }
1602 }
1603 if (output == AUDIO_IO_HANDLE_NONE) {
1604 // No output open with the preferred profile. Open a new one.
1605 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1606 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1607 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1608 config.format = prefMixerConfigInfo->getConfigBase().format;
1609 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1610 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1611 &config, prefMixerConfigInfo->getFlags());
1612 if (preferredOutput == nullptr) {
1613 ALOGE("%s failed to open output with preferred mixer config", __func__);
1614 } else {
1615 output = preferredOutput->mIoHandle;
1616 }
1617 }
1618 } else {
1619 // at this stage we should ignore the DIRECT flag as no direct output could be
1620 // found earlier
1621 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1622 output = selectOutput(
1623 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1624 }
Eric Laurente552edb2014-03-10 17:42:56 -07001625 }
François Gaffie11d30102018-11-02 16:09:09 +01001626 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001627 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001628 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001629
Eric Laurente552edb2014-03-10 17:42:56 -07001630 return output;
1631}
1632
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001633sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001634 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1635 mAvailableInputDevices);
1636 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1637}
1638
1639DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1640 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1641 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001642}
1643
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001644const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001645 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001646 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1647 if (msdModule != 0) {
1648 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1649 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1650 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1651 const struct audio_port_config *source = &patch->mPatch.sources[j];
1652 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1653 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001654 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001655 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001656 }
1657 }
1658 }
1659 return msdPatches;
1660}
1661
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001662bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1663 ssize_t index = mAudioPatches.indexOfKey(handle);
1664 if (index < 0) {
1665 return false;
1666 }
1667 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1668 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1669 if (msdModule == nullptr) {
1670 return false;
1671 }
1672 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1673 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1674 return true;
1675 }
1676 index = getMsdOutputPatches().indexOfKey(handle);
1677 if (index < 0) {
1678 return false;
1679 }
1680 return true;
1681}
1682
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001683status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1684 const InputProfileCollection &inputProfiles,
1685 const OutputProfileCollection &outputProfiles,
1686 const sp<DeviceDescriptor> &sourceDevice,
1687 const sp<DeviceDescriptor> &sinkDevice,
1688 AudioProfileVector& sourceProfiles,
1689 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001690 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001691 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001692 return NO_INIT;
1693 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001694 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001695 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001696 return NO_INIT;
1697 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001698 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001699 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1700 inProfile->supportsDevice(sourceDevice)) {
1701 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001702 }
1703 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001704 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001705 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001706 outProfile->supportsDevice(sinkDevice)) {
1707 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001708 }
1709 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001710 return NO_ERROR;
1711}
1712
1713status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1714 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1715 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1716{
Dean Wheatley16809da2022-12-09 14:55:46 +11001717 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1718 static const std::vector<audio_format_t> formatsOrder = {{
1719 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1720 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1721 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1722 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1723 // preferred).
1724 std::vector<audio_channel_mask_t> masks = {{
1725 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1726 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1727 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1728 // insert index masks (higher counts most preferred) as preferred over position masks
1729 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1730 masks.insert(
1731 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1732 }
1733 return masks;
1734 }();
1735
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001736 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001737 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1738 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001739 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001740 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1741 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001742 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001743 }
1744 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1745 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1746 sinkConfig->format = bestSinkConfig.format;
1747 // For encoded streams force direct flag to prevent downstream mixing.
1748 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1749 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001750 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1751 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001752 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001753 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1754 // raw and IEC61937 framed streams.
1755 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1756 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1757 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001758 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1759 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001760 sourceConfig->channel_mask =
1761 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1762 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1763 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001764 sourceConfig->format = bestSinkConfig.format;
1765 // Copy input stream directly without any processing (e.g. resampling).
1766 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1767 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1768 if (hwAvSync) {
1769 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1770 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1771 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1772 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1773 }
1774 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1775 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1776 sinkConfig->config_mask |= config_mask;
1777 sourceConfig->config_mask |= config_mask;
1778 return NO_ERROR;
1779}
1780
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001781PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1782 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001783{
1784 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001785 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1786 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1787 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1788 if (deviceModule == nullptr) {
1789 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1790 return patchBuilder;
1791 }
1792 const InputProfileCollection inputProfiles = msdIsSource ?
1793 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1794 const OutputProfileCollection outputProfiles = msdIsSource ?
1795 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1796
1797 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1798 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1799 device : getMsdAudioOutDevices().itemAt(0);
1800 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1801
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001802 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1803 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001804 AudioProfileVector sourceProfiles;
1805 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001806 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1807 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001808 for (auto hwAvSync : { true, false }) {
1809 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1810 sourceProfiles, sinkProfiles) != NO_ERROR) {
1811 continue;
1812 }
1813 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1814 &sinkConfig) == NO_ERROR) {
1815 // Found a matching config. Re-create PatchBuilder with this config.
1816 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1817 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001818 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001819 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001820 " supporting PCM format conversion.", __func__);
1821 return patchBuilder;
1822}
1823
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001824status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001825 DeviceVector devices;
1826 if (outputDevices != nullptr && outputDevices->size() > 0) {
1827 devices.add(*outputDevices);
1828 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001829 // Use media strategy for unspecified output device. This should only
1830 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1831 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001832 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001833 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001834 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001835 }
Michael Chan6fb34492020-12-08 15:44:49 +11001836 std::vector<PatchBuilder> patchesToCreate;
1837 for (auto i = 0u; i < devices.size(); ++i) {
1838 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001839 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001840 }
1841 // Retain only the MSD patches associated with outputDevices request.
1842 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001843 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001844 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1845 auto retainedPatch = false;
1846 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1847 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1848 patchesToRemove.removeItemsAt(i);
1849 retainedPatch = true;
1850 break;
1851 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001852 }
Michael Chan6fb34492020-12-08 15:44:49 +11001853 if (retainedPatch) {
1854 it = patchesToCreate.erase(it);
1855 continue;
1856 }
1857 ++it;
1858 }
1859 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1860 return NO_ERROR;
1861 }
1862 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1863 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001864 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001865 }
Michael Chan6fb34492020-12-08 15:44:49 +11001866 status_t status = NO_ERROR;
1867 for (const auto &p : patchesToCreate) {
1868 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1869 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1870 char message[256];
1871 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1872 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1873 currStatus == NO_ERROR ? "Success" : "Error",
1874 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1875 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1876 if (currStatus == NO_ERROR) {
1877 ALOGD("%s", message);
1878 } else {
1879 ALOGE("%s", message);
1880 if (status == NO_ERROR) {
1881 status = currStatus;
1882 }
1883 }
1884 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001885 return status;
1886}
1887
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001888void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1889 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001890 for (size_t i = 0; i < msdPatches.size(); i++) {
1891 const auto& patch = msdPatches[i];
1892 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1893 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1894 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1895 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1896 releaseAudioPatch(patch->getHandle(), mUidCached);
1897 break;
1898 }
1899 }
1900 }
1901}
1902
Dorin Drimus94d94412022-02-02 09:05:02 +01001903bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1904 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1905 AudioPatchCollection msdPatches = getMsdOutputPatches();
1906 for (size_t i = 0; i < msdPatches.size(); i++) {
1907 const auto& patch = msdPatches[i];
1908 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1909 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1910 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1911 const auto& foundDevice = devicesToCheck.getDevice(
1912 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1913 if (foundDevice != nullptr) {
1914 devicesToCheck.remove(foundDevice);
1915 if (devicesToCheck.isEmpty()) {
1916 return true;
1917 }
1918 }
1919 }
1920 }
1921 }
1922 return false;
1923}
1924
Eric Laurente0720872014-03-11 09:30:41 -07001925audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001926 audio_output_flags_t flags,
1927 audio_format_t format,
1928 audio_channel_mask_t channelMask,
1929 uint32_t samplingRate,
1930 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001931{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001932 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1933 "%s called with format %#x", __func__, format);
1934
jiabinebb6af42020-06-09 17:31:17 -07001935 // Return the output that haptic-generating attached to when 1) session id is specified,
1936 // 2) haptic-generating effect exists for given session id and 3) the output that
1937 // haptic-generating effect attached to is in given outputs.
1938 if (sessionId != AUDIO_SESSION_NONE) {
1939 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1940 sessionId, FX_IID_HAPTICGENERATOR);
1941 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1942 return hapticGeneratingOutput;
1943 }
1944 }
1945
Eric Laurent16c66dd2019-05-01 17:54:10 -07001946 // Flags disqualifying an output: the match must happen before calling selectOutput()
1947 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1948 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1949
1950 // Flags expressing a functional request: must be honored in priority over
1951 // other criteria
1952 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1953 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001954 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1955 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001956 // Flags expressing a performance request: have lower priority than serving
1957 // requested sampling rate or channel mask
1958 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1959 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1960 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1961
1962 const audio_output_flags_t functionalFlags =
1963 (audio_output_flags_t)(flags & kFunctionalFlags);
1964 const audio_output_flags_t performanceFlags =
1965 (audio_output_flags_t)(flags & kPerformanceFlags);
1966
1967 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1968
Eric Laurente552edb2014-03-10 17:42:56 -07001969 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001970 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001971 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001972 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001973 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001974 // with tiebreak preferring the minimum number of extra functional flags
1975 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001976 // 3: the output supporting the exact channel mask
1977 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00001978 // 5: the output with the highest sampling rate if the requested sample rate is
1979 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001980 // 6: the output with the highest number of requested performance flags
1981 // 7: the output with the bit depth the closest to the requested one
1982 // 8: the primary output
1983 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001984
Eric Laurent16c66dd2019-05-01 17:54:10 -07001985 // matching criteria values in priority order for best matching output so far
1986 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001987
Eric Laurent16c66dd2019-05-01 17:54:10 -07001988 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1989 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1990 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001991
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001992 for (audio_io_handle_t output : outputs) {
1993 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001994 // matching criteria values in priority order for current output
1995 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001996
Eric Laurent16c66dd2019-05-01 17:54:10 -07001997 if (outputDesc->isDuplicated()) {
1998 continue;
1999 }
2000 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2001 continue;
2002 }
Eric Laurent8838a382014-09-08 16:44:28 -07002003
Eric Laurent16c66dd2019-05-01 17:54:10 -07002004 // If haptic channel is specified, use the haptic output if present.
2005 // When using haptic output, same audio format and sample rate are required.
2006 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002007 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002008 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2009 continue;
2010 }
2011 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002012 && format == outputDesc->getFormat()
2013 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002014 currentMatchCriteria[0] = outputHapticChannelCount;
2015 }
2016
2017 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002018 const int matchingFunctionalFlags =
2019 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2020 const int totalFunctionalFlags =
2021 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2022 // Prefer matching functional flags, but subtract unnecessary functional flags.
2023 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002024
2025 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002026 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2027 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002028 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2029 channelCount <= outputChannelCount) {
2030 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002031 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2032 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002033 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002034 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002035 currentMatchCriteria[3] = outputChannelCount;
2036 }
2037
2038 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002039 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002040 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002041 }
2042
2043 // performance flags match
2044 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2045
2046 // format match
2047 if (format != AUDIO_FORMAT_INVALID) {
2048 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002049 PolicyAudioPort::kFormatDistanceMax -
2050 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002051 }
2052
2053 // primary output match
2054 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2055
2056 // compare match criteria by priority then value
2057 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2058 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2059 bestMatchCriteria = currentMatchCriteria;
2060 bestOutput = output;
2061
2062 std::stringstream result;
2063 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2064 std::ostream_iterator<int>(result, " "));
2065 ALOGV("%s new bestOutput %d criteria %s",
2066 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002067 }
2068 }
2069
Eric Laurent16c66dd2019-05-01 17:54:10 -07002070 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002071}
2072
Eric Laurent8fc147b2018-07-22 19:13:55 -07002073status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002074{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002075 ALOGV("%s portId %d", __FUNCTION__, portId);
2076
2077 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2078 if (outputDesc == 0) {
2079 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002080 return BAD_VALUE;
2081 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002082 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002083
Eric Laurent8fc147b2018-07-22 19:13:55 -07002084 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002085 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002086
Eric Laurent733ce942017-12-07 12:18:25 -08002087 status_t status = outputDesc->start();
2088 if (status != NO_ERROR) {
2089 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002090 }
2091
Eric Laurent97ac8712018-07-27 18:59:02 -07002092 uint32_t delayMs;
2093 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002094
2095 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002096 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002097 if (status == DEAD_OBJECT) {
2098 sp<SwAudioOutputDescriptor> desc =
2099 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2100 if (desc == nullptr) {
2101 // This is not common, it may indicate something wrong with the HAL.
2102 ALOGE("%s unable to open output with default config", __func__);
2103 return status;
2104 }
2105 desc->mUsePreferredMixerAttributes = true;
2106 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002107 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002108 }
jiabina84c3d32022-12-02 18:59:55 +00002109
2110 // If the client is the first one active on preferred mixer parameters, reopen the output
2111 // if the current mixer parameters doesn't match the preferred one.
2112 if (outputDesc->devices().size() == 1) {
2113 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2114 outputDesc->devices()[0]->getId(), client->strategy());
2115 if (info != nullptr && info->getUid() == client->uid()) {
2116 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2117 info->getConfigBase(), info->getFlags())) {
2118 stopSource(outputDesc, client);
2119 outputDesc->stop();
2120 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2121 config.channel_mask = info->getConfigBase().channel_mask;
2122 config.sample_rate = info->getConfigBase().sample_rate;
2123 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002124 sp<SwAudioOutputDescriptor> desc =
2125 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2126 if (desc == nullptr) {
2127 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002128 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002129 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002130 // Intentionally return error to let the client side resending request for
2131 // creating and starting.
2132 return DEAD_OBJECT;
2133 }
2134 info->increaseActiveClient();
2135 }
2136 }
2137
Eric Laurentc75307b2015-03-17 15:29:32 -07002138 if (delayMs != 0) {
2139 usleep(delayMs * 1000);
2140 }
2141
2142 return status;
2143}
2144
Eric Laurent96d1dda2022-03-14 17:14:19 +01002145bool AudioPolicyManager::isLeUnicastActive() const {
2146 if (isInCall()) {
2147 return true;
2148 }
2149 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2150}
2151
2152bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2153 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2154 return false;
2155 }
2156 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2157 ALOGV("%s active %d", __func__, active);
2158 return active;
2159}
2160
Eric Laurent97ac8712018-07-27 18:59:02 -07002161status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2162 const sp<TrackClientDescriptor>& client,
2163 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002164{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002165 // cannot start playback of STREAM_TTS if any other output is being used
2166 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002167
2168 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002169 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002170 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002171 auto clientStrategy = client->strategy();
2172 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002173 if (stream == AUDIO_STREAM_TTS) {
2174 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002175 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002176 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002177 return INVALID_OPERATION;
2178 } else {
2179 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2180 }
2181 } else {
2182 // some playback other than beacon starts
2183 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2184 }
2185
Eric Laurent77305a62016-07-25 16:39:22 -07002186 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002187 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002188 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002189
François Gaffie11d30102018-11-02 16:09:09 +01002190 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002191 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002192 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002193 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002194 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002195 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002196 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002197 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002198 } else {
2199 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002200 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002201 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2202 AUDIO_FORMAT_DEFAULT);
2203 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2204 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002205 }
2206
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002207 // requiresMuteCheck is false when we can bypass mute strategy.
2208 // It covers a common case when there is no materially active audio
2209 // and muting would result in unnecessary delay and dropped audio.
2210 const uint32_t outputLatencyMs = outputDesc->latency();
2211 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002212 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002213
Eric Laurente552edb2014-03-10 17:42:56 -07002214 // increment usage count for this stream on the requested output:
2215 // NOTE that the usage count is the same for duplicated output and hardware output which is
2216 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002217 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002218
2219 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002220 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2221 client->isPreferredDeviceForExclusiveUse()) {
2222 // Preferred device may be exclusive, use only if no other active clients on this output
2223 devices = DeviceVector(
2224 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2225 } else {
2226 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2227 }
François Gaffie11d30102018-11-02 16:09:09 +01002228 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002229 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002230 }
2231 }
Eric Laurente552edb2014-03-10 17:42:56 -07002232
François Gaffiec005e562018-11-06 15:04:49 +01002233 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002234 selectOutputForMusicEffects();
2235 }
2236
François Gaffie1c878552018-11-22 16:53:21 +01002237 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002238 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002239 if (devices.isEmpty()) {
2240 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002241 }
François Gaffiec005e562018-11-06 15:04:49 +01002242 bool shouldWait =
2243 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2244 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2245 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002246 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002247 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002248 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002249 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002250 // An output has a shared device if
2251 // - managed by the same hw module
2252 // - supports the currently selected device
2253 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002254 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002255
Eric Laurent77305a62016-07-25 16:39:22 -07002256 // force a device change if any other output is:
2257 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002258 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002259 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002260 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002261 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002262 // change the device currently selected by the other output.
2263 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002264 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002265 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002266 force = true;
2267 }
2268 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002269 // a notification so that audio focus effect can propagate, or that a mute/unmute
2270 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002271 const uint32_t latencyMs = desc->latency();
2272 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2273
2274 if (shouldWait && isActive && (waitMs < latencyMs)) {
2275 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002276 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002277
2278 // Require mute check if another output is on a shared device
2279 // and currently active to have proper drain and avoid pops.
2280 // Note restoring AudioTracks onto this output needs to invoke
2281 // a volume ramp if there is no mute.
2282 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002283 }
2284 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002285
jiabin3ff8d7d2022-12-13 06:27:44 +00002286 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2287 // If the output is open with preferred mixer attributes, but the routed device is
2288 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2289 // changed.
2290 return DEAD_OBJECT;
2291 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002292 const uint32_t muteWaitMs =
jiabin3ff8d7d2022-12-13 06:27:44 +00002293 setOutputDevices(outputDesc, devices, force, 0, nullptr, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002294
Eric Laurente552edb2014-03-10 17:42:56 -07002295 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002296 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002297 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002298 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002299 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002300 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002301 outputDesc->useHwGain() /*force*/)) {
2302 // request AudioService to reinitialize the volume curves asynchronously
2303 ALOGE("checkAndSetVolume failed, requesting volume range init");
2304 mpClientInterface->onVolumeRangeInitRequest();
2305 };
Eric Laurente552edb2014-03-10 17:42:56 -07002306
2307 // update the outputs if starting an output with a stream that can affect notification
2308 // routing
2309 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002310
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002311 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002312 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002313 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002314 }
Eric Laurentdc462862016-07-19 12:29:53 -07002315
2316 if (waitMs > muteWaitMs) {
2317 *delayMs = waitMs - muteWaitMs;
2318 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002319
2320 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2321 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2322 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2323 // change occurs after the MixerThread starts and causes a stream volume
2324 // glitch.
2325 //
2326 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002327 }
Eric Laurentdc462862016-07-19 12:29:53 -07002328
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002329 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002330 mEngine->getForceUse(
2331 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002332 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002333 }
2334
Eric Laurent97ac8712018-07-27 18:59:02 -07002335 // Automatically enable the remote submix input when output is started on a re routing mix
2336 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002337 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2338 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002339 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2340 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2341 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002342 "remote-submix",
2343 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002344 }
2345
Eric Laurent96d1dda2022-03-14 17:14:19 +01002346 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2347
Eric Laurente552edb2014-03-10 17:42:56 -07002348 return NO_ERROR;
2349}
2350
Eric Laurent96d1dda2022-03-14 17:14:19 +01002351void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2352 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2353 bool isUnicastActive = isLeUnicastActive();
2354
2355 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002356 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002357 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2358 for (size_t i = 0; i < mOutputs.size(); i++) {
2359 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2360 if (desc != ignoredOutput && desc->isActive()
2361 && ((isUnicastActive &&
2362 !desc->devices().
2363 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2364 || (wasUnicastActive &&
2365 !desc->devices().getDevicesFromTypes(
2366 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2367 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2368 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002369 if (desc->mUsePreferredMixerAttributes && force) {
2370 // If the device is using preferred mixer attributes, the output need to reopen
2371 // with default configuration when the new selected devices are different from
2372 // current routing devices.
2373 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2374 continue;
2375 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002376 setOutputDevices(desc, newDevices, force, delayMs);
2377 // re-apply device specific volume if not done by setOutputDevice()
2378 if (!force) {
2379 applyStreamVolumes(desc, newDevices.types(), delayMs);
2380 }
2381 }
2382 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002383 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002384 }
2385}
2386
Eric Laurent8fc147b2018-07-22 19:13:55 -07002387status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002388{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002389 ALOGV("%s portId %d", __FUNCTION__, portId);
2390
2391 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2392 if (outputDesc == 0) {
2393 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002394 return BAD_VALUE;
2395 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002396 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002397
Eric Laurent97ac8712018-07-27 18:59:02 -07002398 ALOGV("stopOutput() output %d, stream %d, session %d",
2399 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002400
Eric Laurent97ac8712018-07-27 18:59:02 -07002401 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002402
Eric Laurent733ce942017-12-07 12:18:25 -08002403 if (status == NO_ERROR ) {
2404 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002405 } else {
2406 return status;
2407 }
2408
2409 if (outputDesc->devices().size() == 1) {
2410 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2411 outputDesc->devices()[0]->getId(), client->strategy());
2412 if (info != nullptr && info->getUid() == client->uid()) {
2413 info->decreaseActiveClient();
2414 if (info->getActiveClientCount() == 0) {
2415 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2416 }
2417 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002418 }
2419 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002420}
2421
Eric Laurent97ac8712018-07-27 18:59:02 -07002422status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2423 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002424{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002425 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002426 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002427 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002428 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002429
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002430 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2431
François Gaffie1c878552018-11-22 16:53:21 +01002432 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2433 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002434 // Automatically disable the remote submix input when output is stopped on a
2435 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002436 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002437 if (isSingleDeviceType(
2438 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002439 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002440 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002441 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2442 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002443 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002444 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002445 }
2446 }
2447 bool forceDeviceUpdate = false;
2448 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002449 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002450 forceDeviceUpdate = true;
2451 }
2452
Eric Laurente552edb2014-03-10 17:42:56 -07002453 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002454 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002455
Eric Laurente552edb2014-03-10 17:42:56 -07002456 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002457 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002458 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002459 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002460
2461 // If the routing does not change, if an output is routed on a device using HwGain
2462 // (aka setAudioPortConfig) and there are still active clients following different
2463 // volume group(s), force reapply volume
2464 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2465 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2466
Eric Laurente552edb2014-03-10 17:42:56 -07002467 // delay the device switch by twice the latency because stopOutput() is executed when
2468 // the track stop() command is received and at that time the audio track buffer can
2469 // still contain data that needs to be drained. The latency only covers the audio HAL
2470 // and kernel buffers. Also the latency does not always include additional delay in the
2471 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002472 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2473 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002474
2475 // force restoring the device selection on other active outputs if it differs from the
2476 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002477 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002478 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002479 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002480 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002481 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002482 desc->isActive() &&
2483 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002484 (newDevices != desc->devices())) {
2485 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2486 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002487
jiabin3ff8d7d2022-12-13 06:27:44 +00002488 if (desc->mUsePreferredMixerAttributes && force) {
2489 // If the device is using preferred mixer attributes, the output need to
2490 // reopen with default configuration when the new selected devices are
2491 // different from current routing devices.
2492 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2493 continue;
2494 }
François Gaffie11d30102018-11-02 16:09:09 +01002495 setOutputDevices(desc, newDevices2, force, delayMs);
2496
Eric Laurent57de36c2016-09-28 16:59:11 -07002497 // re-apply device specific volume if not done by setOutputDevice()
2498 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002499 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002500 }
Eric Laurente552edb2014-03-10 17:42:56 -07002501 }
2502 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002503 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002504 // update the outputs if stopping one with a stream that can affect notification routing
2505 handleNotificationRoutingForStream(stream);
2506 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002507
2508 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2509 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002510 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002511 }
2512
François Gaffiec005e562018-11-06 15:04:49 +01002513 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002514 selectOutputForMusicEffects();
2515 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002516
2517 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2518
Eric Laurente552edb2014-03-10 17:42:56 -07002519 return NO_ERROR;
2520 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002521 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002522 return INVALID_OPERATION;
2523 }
2524}
2525
jiabinbce0c1d2020-10-05 11:20:18 -07002526bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002527{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002528 ALOGV("%s portId %d", __FUNCTION__, portId);
2529
2530 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2531 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002532 // If an output descriptor is closed due to a device routing change,
2533 // then there are race conditions with releaseOutput from tracks
2534 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2535 // destroyed shortly thereafter.
2536 //
2537 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002538 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002539 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002540 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002541
2542 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002543
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302544 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2545 if (outputDesc->isClientActive(client)) {
2546 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2547 stopOutput(portId);
2548 }
2549
Eric Laurent8fc147b2018-07-22 19:13:55 -07002550 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2551 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002552 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002553 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002554 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002555 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002556 if (--outputDesc->mDirectOpenCount == 0) {
2557 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002558 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002559 }
2560 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302561
Andy Hung39efb7a2018-09-26 15:39:28 -07002562 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002563 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2564 // The output is pending reopened to query dynamic profiles and
2565 // there is no active clients
2566 closeOutput(outputDesc->mIoHandle);
2567 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2568 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2569 if (newOutputDesc == nullptr) {
2570 ALOGE("%s failed to open output", __func__);
2571 }
2572 return true;
2573 }
2574 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002575}
2576
Eric Laurentcaf7f482014-11-25 17:50:47 -08002577status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2578 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002579 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002580 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002581 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002582 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002583 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002584 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002585 input_type_t *inputType,
2586 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002587{
François Gaffiec005e562018-11-06 15:04:49 +01002588 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002589 "flags %#x attributes=%s requested device ID %d",
2590 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2591 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002592
Eric Laurentad2e7b92017-09-14 20:06:42 -07002593 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002594 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002595 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002596 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002597 sp<AudioInputDescriptor> inputDesc;
2598 sp<RecordClientDescriptor> clientDesc;
2599 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002600 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002601 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002602
2603 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2604 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2605 return INVALID_OPERATION;
2606 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002607
Francois Gaffie716e1432019-01-14 16:58:59 +01002608 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2609 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002610 }
2611
Paul McLean466dc8e2015-04-17 13:15:36 -06002612 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002613 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002614 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002615
Eric Laurentad2e7b92017-09-14 20:06:42 -07002616 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2617 // possible
2618 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2619 *input != AUDIO_IO_HANDLE_NONE) {
2620 ssize_t index = mInputs.indexOfKey(*input);
2621 if (index < 0) {
2622 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2623 status = BAD_VALUE;
2624 goto error;
2625 }
2626 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002627 RecordClientVector clients = inputDesc->getClientsForSession(session);
2628 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002629 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2630 status = BAD_VALUE;
2631 goto error;
2632 }
2633 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2634 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002635 // corresponds to a new client and is only permitted from the same UID.
2636 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002637 if (clients.size() > 1) {
2638 for (const auto& client : clients) {
2639 // The client map is ordered by key values (portId) and portIds are allocated
2640 // incrementaly. So the first client in this list is the one opened by audio flinger
2641 // when the mmap stream is created and should be ignored as it does not correspond
2642 // to an actual client
2643 if (client == *clients.cbegin()) {
2644 continue;
2645 }
2646 if (uid != client->uid() && !client->isSilenced()) {
2647 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2648 uid, client->portId(), client->uid());
2649 status = INVALID_OPERATION;
2650 goto error;
2651 }
Eric Laurent331679c2018-04-16 17:03:16 -07002652 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002653 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002654 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002655 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002656
Eric Laurentfecbceb2021-02-09 14:46:43 +01002657 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002658 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002659 }
2660
2661 *input = AUDIO_IO_HANDLE_NONE;
2662 *inputType = API_INPUT_INVALID;
2663
Francois Gaffie716e1432019-01-14 16:58:59 +01002664 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002665 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002666 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002667 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002668 ALOGW("%s could not find input mix for attr %s",
2669 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002670 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002671 }
jiabinc1de2df2019-05-07 14:26:40 -07002672 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2673 String8(attr->tags + strlen("addr=")),
2674 AUDIO_FORMAT_DEFAULT);
2675 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002676 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002677 __func__, attributes.source, attributes.tags);
2678 status = BAD_VALUE;
2679 goto error;
2680 }
2681
Kevin Rocard25f9b052019-02-27 15:08:54 -08002682 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2683 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2684 } else {
2685 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2686 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002687 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002688 if (explicitRoutingDevice != nullptr) {
2689 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002690 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002691 // Prevent from storing invalid requested device id in clients
2692 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002693 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002694 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2695 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002696 }
François Gaffie11d30102018-11-02 16:09:09 +01002697 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002698 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002699 status = BAD_VALUE;
2700 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002701 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002702 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2703 *inputType = API_INPUT_MIX_CAPTURE;
2704 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002705 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2706 // there is an external policy, but this input is attached to a mix of recorders,
2707 // meaning it receives audio injected into the framework, so the recorder doesn't
2708 // know about it and is therefore considered "legacy"
2709 *inputType = API_INPUT_LEGACY;
2710 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002711 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002712 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002713 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002714 } else {
2715 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002716 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002717
Eric Laurent599c7582015-12-07 18:05:55 -08002718 }
2719
François Gaffiec005e562018-11-06 15:04:49 +01002720 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002721 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002722 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002723 AudioProfileVector profiles;
2724 status_t ret = getProfilesForDevices(
2725 DeviceVector(device), profiles, flags, true /*isInput*/);
2726 if (ret == NO_ERROR && !profiles.empty()) {
2727 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
2728 : *profiles[0]->getChannels().begin();
2729 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
2730 : *profiles[0]->getSampleRates().begin();
2731 config->format = profiles[0]->getFormat();
2732 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002733 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002734 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002735
Eric Laurent8f42ea12018-08-08 09:08:25 -07002736exit:
2737
François Gaffiec005e562018-11-06 15:04:49 +01002738 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2739 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002740
Francois Gaffie716e1432019-01-14 16:58:59 +01002741 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002742 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002743 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002744
Mikhail Naganov2996f672019-04-18 12:29:59 -07002745 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002746 requestedDeviceId, attributes.source, flags,
2747 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002748 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002749 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002750
2751 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2752 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002753
Eric Laurent599c7582015-12-07 18:05:55 -08002754 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002755
2756error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002757 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002758}
2759
2760
François Gaffie11d30102018-11-02 16:09:09 +01002761audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002762 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002763 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002764 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002765 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002766 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002767{
2768 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002769 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002770 bool isSoundTrigger = false;
2771
François Gaffiec005e562018-11-06 15:04:49 +01002772 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002773 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2774 if (index >= 0) {
2775 input = mSoundTriggerSessions.valueFor(session);
2776 isSoundTrigger = true;
2777 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2778 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2779 } else {
2780 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002781 }
François Gaffiec005e562018-11-06 15:04:49 +01002782 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002783 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002784 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002785 }
2786
Carter Hsua3abb402021-10-26 11:11:20 +08002787 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2788 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2789 }
2790
Eric Laurentfe231122017-11-17 17:48:06 -08002791 // sampling rate and flags may be updated by getInputProfile
2792 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2793 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002794 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002795 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002796 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002797 // find a compatible input profile (not necessarily identical in parameters)
2798 sp<IOProfile> profile = getInputProfile(
2799 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2800 if (profile == nullptr) {
2801 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002802 }
jiabin2fd710d2022-05-02 23:20:22 +00002803
Glenn Kasten05ddca52016-02-11 08:17:12 -08002804 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002805 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002806 if (samplingRate == 0) {
2807 samplingRate = profileSamplingRate;
2808 }
Eric Laurente552edb2014-03-10 17:42:56 -07002809
Eric Laurent322b4d22015-04-03 15:57:54 -07002810 if (profile->getModuleHandle() == 0) {
2811 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002812 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002813 }
2814
Eric Laurentec376dc2021-04-08 20:41:22 +02002815 // Reuse an already opened input if a client with the same session ID already exists
2816 // on that input
2817 for (size_t i = 0; i < mInputs.size(); i++) {
2818 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2819 if (desc->mProfile != profile) {
2820 continue;
2821 }
2822 RecordClientVector clients = desc->clientsList();
2823 for (const auto &client : clients) {
2824 if (session == client->session()) {
2825 return desc->mIoHandle;
2826 }
2827 }
2828 }
2829
Eric Laurent3974e3b2017-12-07 17:58:43 -08002830 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002831 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002832 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002833 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002834 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002835 continue;
2836 }
2837 // if sound trigger, reuse input if used by other sound trigger on same session
2838 // else
2839 // reuse input if active client app is not in IDLE state
2840 //
2841 RecordClientVector clients = desc->clientsList();
2842 bool doClose = false;
2843 for (const auto& client : clients) {
2844 if (isSoundTrigger != client->isSoundTrigger()) {
2845 continue;
2846 }
2847 if (client->isSoundTrigger()) {
2848 if (session == client->session()) {
2849 return desc->mIoHandle;
2850 }
2851 continue;
2852 }
2853 if (client->active() && client->appState() != APP_STATE_IDLE) {
2854 return desc->mIoHandle;
2855 }
2856 doClose = true;
2857 }
2858 if (doClose) {
2859 closeInput(desc->mIoHandle);
2860 } else {
2861 i++;
2862 }
2863 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002864 }
2865
Eric Laurentfe231122017-11-17 17:48:06 -08002866 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002867
Eric Laurentfe231122017-11-17 17:48:06 -08002868 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2869 lConfig.sample_rate = profileSamplingRate;
2870 lConfig.channel_mask = profileChannelMask;
2871 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002872
François Gaffie11d30102018-11-02 16:09:09 +01002873 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002874
2875 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002876 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002877 (profileSamplingRate != lConfig.sample_rate) ||
2878 !audio_formats_match(profileFormat, lConfig.format) ||
2879 (profileChannelMask != lConfig.channel_mask)) {
2880 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002881 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002882 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002883 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002884 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002885 }
Eric Laurent599c7582015-12-07 18:05:55 -08002886 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002887 }
2888
Eric Laurentc722f302014-12-10 11:21:49 -08002889 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002890
Eric Laurent599c7582015-12-07 18:05:55 -08002891 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002892 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002893
Eric Laurent599c7582015-12-07 18:05:55 -08002894 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002895}
2896
Eric Laurent4eb58f12018-12-07 16:41:02 -08002897status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002898{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002899 ALOGV("%s portId %d", __FUNCTION__, portId);
2900
2901 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2902 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002903 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002904 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002905 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002906 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002907 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002908 if (client->active()) {
2909 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2910 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002911 }
2912
Eric Laurent8f42ea12018-08-08 09:08:25 -07002913 audio_session_t session = client->session();
2914
Eric Laurent4eb58f12018-12-07 16:41:02 -08002915 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002916
Eric Laurent4eb58f12018-12-07 16:41:02 -08002917 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002918
Eric Laurent4eb58f12018-12-07 16:41:02 -08002919 status_t status = inputDesc->start();
2920 if (status != NO_ERROR) {
2921 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002922 }
Eric Laurente552edb2014-03-10 17:42:56 -07002923
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002924 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002925 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002926 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002927
Eric Laurent8f42ea12018-08-08 09:08:25 -07002928 // indicate active capture to sound trigger service if starting capture from a mic on
2929 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002930 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002931 if (device != nullptr) {
2932 status = setInputDevice(input, device, true /* force */);
2933 } else {
2934 ALOGW("%s no new input device can be found for descriptor %d",
2935 __FUNCTION__, inputDesc->getId());
2936 status = BAD_VALUE;
2937 }
Eric Laurente552edb2014-03-10 17:42:56 -07002938
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002939 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002940 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002941 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002942 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002943 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2944 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002945 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002946 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002947
François Gaffie11d30102018-11-02 16:09:09 +01002948 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2949 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002950 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002951 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002952 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002953
Eric Laurent8f42ea12018-08-08 09:08:25 -07002954 // automatically enable the remote submix output when input is started if not
2955 // used by a policy mix of type MIX_TYPE_RECORDERS
2956 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002957 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002958 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002959 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002960 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002961 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2962 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002963 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002964 if (address != "") {
2965 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2966 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002967 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002968 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002969 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002970 } else if (status != NO_ERROR) {
2971 // Restore client activity state.
2972 inputDesc->setClientActive(client, false);
2973 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002974 }
2975
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002976 ALOGV("%s input %d source = %d status = %d exit",
2977 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002978
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002979 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002980}
2981
Eric Laurent8fc147b2018-07-22 19:13:55 -07002982status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002983{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002984 ALOGV("%s portId %d", __FUNCTION__, portId);
2985
2986 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2987 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002988 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002989 return BAD_VALUE;
2990 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002991 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002992 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002993 if (!client->active()) {
2994 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002995 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002996 }
Carter Hsue6139d52021-07-08 10:30:20 +08002997 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002998 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002999
Eric Laurent8f42ea12018-08-08 09:08:25 -07003000 inputDesc->stop();
3001 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003002 auto current_source = inputDesc->source();
3003 setInputDevice(input, getNewInputDevice(inputDesc),
3004 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003005 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003006 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003007 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003008 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003009 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3010 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003011 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003012 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003013
3014 // automatically disable the remote submix output when input is stopped if not
3015 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003016 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003017 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003018 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003019 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003020 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3021 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003022 }
3023 if (address != "") {
3024 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3025 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003026 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003027 }
3028 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003029 resetInputDevice(input);
3030
3031 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3032 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003033 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3034 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003035 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003036 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003037 }
3038 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003039 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003040 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003041}
3042
Eric Laurent8fc147b2018-07-22 19:13:55 -07003043void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003044{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003045 ALOGV("%s portId %d", __FUNCTION__, portId);
3046
3047 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3048 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003049 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003050 return;
3051 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003052 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003053 audio_io_handle_t input = inputDesc->mIoHandle;
3054
Eric Laurent8f42ea12018-08-08 09:08:25 -07003055 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003056
Andy Hung39efb7a2018-09-26 15:39:28 -07003057 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08003058
Andy Hung39efb7a2018-09-26 15:39:28 -07003059 if (inputDesc->getClientCount() > 0) {
3060 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003061 return;
3062 }
3063
Eric Laurent05b90f82014-08-27 15:32:29 -07003064 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003065 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003066 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003067}
3068
Eric Laurent8f42ea12018-08-08 09:08:25 -07003069void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003070{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003071 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003072
3073 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003074 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003075 }
3076}
3077
Eric Laurent8f42ea12018-08-08 09:08:25 -07003078void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3079{
3080 stopInput(portId);
3081 releaseInput(portId);
3082}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003083
Eric Laurent0dd51852019-04-19 18:18:58 -07003084void AudioPolicyManager::checkCloseInputs() {
3085 // After connecting or disconnecting an input device, close input if:
3086 // - it has no client (was just opened to check profile) OR
3087 // - none of its supported devices are connected anymore OR
3088 // - one of its clients cannot be routed to one of its supported
3089 // devices anymore. Otherwise update device selection
3090 std::vector<audio_io_handle_t> inputsToClose;
3091 for (size_t i = 0; i < mInputs.size(); i++) {
3092 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3093 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003094 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003095 inputsToClose.push_back(mInputs.keyAt(i));
3096 } else {
3097 bool close = false;
3098 for (const auto& client : input->clientsList()) {
3099 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003100 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3101 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003102 if (!input->supportedDevices().contains(device)) {
3103 close = true;
3104 break;
3105 }
3106 }
3107 if (close) {
3108 inputsToClose.push_back(mInputs.keyAt(i));
3109 } else {
3110 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3111 }
3112 }
3113 }
3114
3115 for (const audio_io_handle_t handle : inputsToClose) {
3116 ALOGV("%s closing input %d", __func__, handle);
3117 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003118 }
Eric Laurentd4692962014-05-05 18:13:44 -07003119}
3120
François Gaffie251c7f02018-11-07 10:41:08 +01003121void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003122{
3123 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003124 if (indexMin < 0 || indexMax < 0) {
3125 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3126 return;
3127 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003128 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003129
3130 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003131 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3132 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003133 continue;
3134 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003135 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003136 }
Eric Laurente552edb2014-03-10 17:42:56 -07003137}
3138
Eric Laurente0720872014-03-11 09:30:41 -07003139status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003140 int index,
3141 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003142{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003143 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003144 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3145 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3146 return NO_ERROR;
3147 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003148 ALOGV("%s: stream %s attributes=%s", __func__,
3149 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003150 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003151}
3152
Eric Laurente0720872014-03-11 09:30:41 -07003153status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003154 int *index,
3155 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003156{
François Gaffiec005e562018-11-06 15:04:49 +01003157 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3158 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003159 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003160 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003161 deviceTypes = mEngine->getOutputDevicesForStream(
3162 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003163 }
jiabin9a3361e2019-10-01 09:38:30 -07003164 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003165}
3166
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003167status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003168 int index,
3169 audio_devices_t device)
3170{
3171 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003172 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3173 if (group == VOLUME_GROUP_NONE) {
3174 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003175 return BAD_VALUE;
3176 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003177 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003178 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003179 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003180 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003181 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3182 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3183 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3184 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003185 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3186
3187 status = setVolumeCurveIndex(index, device, curves);
3188 if (status != NO_ERROR) {
3189 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3190 return status;
3191 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003192
jiabin9a3361e2019-10-01 09:38:30 -07003193 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003194 auto curCurvAttrs = curves.getAttributes();
3195 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3196 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003197 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003198 } else if (!curves.getStreamTypes().empty()) {
3199 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003200 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003201 } else {
3202 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3203 return BAD_VALUE;
3204 }
jiabin9a3361e2019-10-01 09:38:30 -07003205 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3206 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003207
François Gaffiecfe17322018-11-07 13:41:29 +01003208 // update volume on all outputs and streams matching the following:
3209 // - The requested stream (or a stream matching for volume control) is active on the output
3210 // - The device (or devices) selected by the engine for this stream includes
3211 // the requested device
3212 // - For non default requested device, currently selected device on the output is either the
3213 // requested device or one of the devices selected by the engine for this stream
3214 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3215 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003216 for (size_t i = 0; i < mOutputs.size(); i++) {
3217 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003218 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003219
jiabin9a3361e2019-10-01 09:38:30 -07003220 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3221 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003222 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003223
3224 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003225 continue;
3226 }
3227 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3228 curDevices.find(device) == curDevices.end()) {
3229 continue;
3230 }
3231 bool applyVolume = false;
3232 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3233 curSrcDevices.insert(device);
3234 applyVolume = (curSrcDevices.find(
3235 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3236 } else {
3237 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3238 }
3239 if (!applyVolume) {
3240 continue; // next output
3241 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003242 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3243 // If a higher priority strategy is active, and the output is routed to a device with a
3244 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003245 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003246 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003247 // If the volume source is active with higher priority source, ensure at least Sw Muted
3248 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003249 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3250 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3251 false /*preferredDevice*/);
3252 if (activeClients.empty()) {
3253 continue;
3254 }
3255 bool isPreempted = false;
3256 bool isHigherPriority = productStrategy < strategy;
3257 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003258 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003259 ALOGV("%s: Strategy=%d (\nrequester:\n"
3260 " group %d, volumeGroup=%d attributes=%s)\n"
3261 " higher priority source active:\n"
3262 " volumeGroup=%d attributes=%s) \n"
3263 " on output %zu, bailing out", __func__, productStrategy,
3264 group, group, toString(attributes).c_str(),
3265 client->volumeSource(), toString(client->attributes()).c_str(), i);
3266 applyVolume = false;
3267 isPreempted = true;
3268 break;
3269 }
3270 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003271 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003272 applyVolume = true;
3273 }
3274 }
3275 if (isPreempted || applyVolume) {
3276 break;
3277 }
3278 }
3279 if (!applyVolume) {
3280 continue; // next output
3281 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003282 }
François Gaffieed91f582020-01-31 10:35:37 +01003283 //FIXME: workaround for truncated touch sounds
3284 // delayed volume change for system stream to be removed when the problem is
3285 // handled by system UI
3286 status_t volStatus = checkAndSetVolume(
3287 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003288 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003289 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3290 if (volStatus != NO_ERROR) {
3291 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003292 }
3293 }
François Gaffiecfe17322018-11-07 13:41:29 +01003294 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3295 return status;
3296}
3297
François Gaffieaaac0fd2018-11-22 17:56:39 +01003298status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003299 audio_devices_t device,
3300 IVolumeCurves &volumeCurves)
3301{
3302 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3303 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003304 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3305 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003306 (index > volumeCurves.getVolumeIndexMax())) {
3307 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3308 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3309 return BAD_VALUE;
3310 }
3311 if (!audio_is_output_device(device)) {
3312 return BAD_VALUE;
3313 }
3314
3315 // Force max volume if stream cannot be muted
3316 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3317
François Gaffieaaac0fd2018-11-22 17:56:39 +01003318 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003319 volumeCurves.addCurrentVolumeIndex(device, index);
3320 return NO_ERROR;
3321}
3322
3323status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3324 int &index,
3325 audio_devices_t device)
3326{
3327 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3328 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003329 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003330 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003331 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003332 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003333 }
jiabin9a3361e2019-10-01 09:38:30 -07003334 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003335}
3336
3337status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3338 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003339 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003340{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003341 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003342 return BAD_VALUE;
3343 }
jiabin9a3361e2019-10-01 09:38:30 -07003344 index = curves.getVolumeIndex(deviceTypes);
3345 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003346 return NO_ERROR;
3347}
3348
3349status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3350 int &index)
3351{
3352 index = getVolumeCurves(attr).getVolumeIndexMin();
3353 return NO_ERROR;
3354}
3355
3356status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3357 int &index)
3358{
3359 index = getVolumeCurves(attr).getVolumeIndexMax();
3360 return NO_ERROR;
3361}
3362
Eric Laurent36829f92017-04-07 19:04:42 -07003363audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003364{
3365 // select one output among several suitable for global effects.
3366 // The priority is as follows:
3367 // 1: An offloaded output. If the effect ends up not being offloadable,
3368 // AudioFlinger will invalidate the track and the offloaded output
3369 // will be closed causing the effect to be moved to a PCM output.
3370 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003371 // 3: The primary output
3372 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003373
François Gaffiec005e562018-11-06 15:04:49 +01003374 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3375 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003376 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003377
Eric Laurent36829f92017-04-07 19:04:42 -07003378 if (outputs.size() == 0) {
3379 return AUDIO_IO_HANDLE_NONE;
3380 }
Eric Laurente552edb2014-03-10 17:42:56 -07003381
Eric Laurent36829f92017-04-07 19:04:42 -07003382 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3383 bool activeOnly = true;
3384
3385 while (output == AUDIO_IO_HANDLE_NONE) {
3386 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3387 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3388 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3389
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003390 for (audio_io_handle_t output : outputs) {
3391 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003392 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003393 continue;
3394 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003395 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3396 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003397 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003398 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003399 }
3400 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003401 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003402 }
3403 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003404 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003405 }
3406 }
3407 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3408 output = outputOffloaded;
3409 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3410 output = outputDeepBuffer;
3411 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3412 output = outputPrimary;
3413 } else {
3414 output = outputs[0];
3415 }
3416 activeOnly = false;
3417 }
3418
3419 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003420 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003421 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3422 mMusicEffectOutput = output;
3423 }
3424
3425 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003426 return output;
3427}
3428
Eric Laurent36829f92017-04-07 19:04:42 -07003429audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3430{
3431 return selectOutputForMusicEffects();
3432}
3433
Eric Laurente0720872014-03-11 09:30:41 -07003434status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003435 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003436 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003437 int session,
3438 int id)
3439{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003440 if (session != AUDIO_SESSION_DEVICE) {
3441 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003442 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003443 index = mInputs.indexOfKey(io);
3444 if (index < 0) {
3445 ALOGW("registerEffect() unknown io %d", io);
3446 return INVALID_OPERATION;
3447 }
Eric Laurente552edb2014-03-10 17:42:56 -07003448 }
3449 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003450 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3451 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3452 || strategy == PRODUCT_STRATEGY_NONE));
3453 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003454}
3455
Eric Laurentc241b0d2018-11-28 09:08:49 -08003456status_t AudioPolicyManager::unregisterEffect(int id)
3457{
3458 if (mEffects.getEffect(id) == nullptr) {
3459 return INVALID_OPERATION;
3460 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003461 if (mEffects.isEffectEnabled(id)) {
3462 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3463 setEffectEnabled(id, false);
3464 }
3465 return mEffects.unregisterEffect(id);
3466}
3467
3468status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3469{
3470 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3471 if (effect == nullptr) {
3472 return INVALID_OPERATION;
3473 }
3474
3475 status_t status = mEffects.setEffectEnabled(id, enabled);
3476 if (status == NO_ERROR) {
3477 mInputs.trackEffectEnabled(effect, enabled);
3478 }
3479 return status;
3480}
3481
Eric Laurent6c796322019-04-09 14:13:17 -07003482
3483status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3484{
3485 mEffects.moveEffects(ids, io);
3486 return NO_ERROR;
3487}
3488
Eric Laurentc75307b2015-03-17 15:29:32 -07003489bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3490{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003491 auto vs = toVolumeSource(stream, false);
3492 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003493}
3494
3495bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3496{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003497 auto vs = toVolumeSource(stream, false);
3498 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003499}
3500
Eric Laurente0720872014-03-11 09:30:41 -07003501bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003502{
3503 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003504 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003505 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003506 return true;
3507 }
3508 }
3509 return false;
3510}
3511
Eric Laurent275e8e92014-11-30 15:14:47 -08003512// Register a list of custom mixes with their attributes and format.
3513// When a mix is registered, corresponding input and output profiles are
3514// added to the remote submix hw module. The profile contains only the
3515// parameters (sampling rate, format...) specified by the mix.
3516// The corresponding input remote submix device is also connected.
3517//
3518// When a remote submix device is connected, the address is checked to select the
3519// appropriate profile and the corresponding input or output stream is opened.
3520//
3521// When capture starts, getInputForAttr() will:
3522// - 1 look for a mix matching the address passed in attribtutes tags if any
3523// - 2 if none found, getDeviceForInputSource() will:
3524// - 2.1 look for a mix matching the attributes source
3525// - 2.2 if none found, default to device selection by policy rules
3526// At this time, the corresponding output remote submix device is also connected
3527// and active playback use cases can be transferred to this mix if needed when reconnecting
3528// after AudioTracks are invalidated
3529//
3530// When playback starts, getOutputForAttr() will:
3531// - 1 look for a mix matching the address passed in attribtutes tags if any
3532// - 2 if none found, look for a mix matching the attributes usage
3533// - 3 if none found, default to device and output selection by policy rules.
3534
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003535status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003536{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003537 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3538 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003539 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003540 sp<HwModule> rSubmixModule;
3541 // examine each mix's route type
3542 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003543 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003544 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3545 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3546 ALOGE("Unsupported Policy Mix %zu of %zu: "
3547 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3548 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003549 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003550 break;
3551 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003552 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3553 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003554 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003555 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3556 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003557 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003558 rSubmixModule = mHwModules.getModuleFromName(
3559 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3560 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003561 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003562 i);
3563 res = INVALID_OPERATION;
3564 break;
3565 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003566 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003567
Eric Laurent97ac8712018-07-27 18:59:02 -07003568 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003569 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003570 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003571 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003572 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3573 } else {
3574 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3575 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003576 }
François Gaffie036e1e92015-03-19 10:16:24 +01003577
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003578 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003579 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003580 res = INVALID_OPERATION;
3581 break;
3582 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003583 audio_config_t outputConfig = mix.mFormat;
3584 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003585 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3586 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003587 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3588 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003589 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003590 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003591 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003592 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003593
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003594 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003595 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3596 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3597 ALOGE("Failed to set remote submix device available, type %u, address %s",
3598 mix.mDeviceType, address.string());
3599 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003600 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003601 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3602 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003603 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003604 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003605 i, mixes.size(), type, address.string());
3606
3607 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3608 mix.mDeviceType, mix.mDeviceAddress,
3609 String8(), AUDIO_FORMAT_DEFAULT);
3610 if (device == nullptr) {
3611 res = INVALID_OPERATION;
3612 break;
3613 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003614
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003615 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003616 // First try to find an already opened output supporting the device
3617 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003618 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003619
Eric Laurentc529cf62020-04-17 18:19:10 -07003620 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003621 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003622 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3623 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003624 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003625 } else {
3626 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003627 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003628 }
3629 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003630 // If no output found, try to find a direct output profile supporting the device
3631 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3632 sp<HwModule> module = mHwModules[i];
3633 for (size_t j = 0;
3634 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3635 j++) {
3636 sp<IOProfile> profile = module->getOutputProfiles()[j];
3637 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3638 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3639 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3640 address.string());
3641 res = INVALID_OPERATION;
3642 } else {
3643 foundOutput = true;
3644 }
3645 }
3646 }
3647 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003648 if (res != NO_ERROR) {
3649 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003650 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003651 res = INVALID_OPERATION;
3652 break;
3653 } else if (!foundOutput) {
3654 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003655 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003656 res = INVALID_OPERATION;
3657 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003658 } else {
3659 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003660 }
Eric Laurentc722f302014-12-10 11:21:49 -08003661 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003662 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003663 if (res != NO_ERROR) {
3664 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003665 } else if (checkOutputs) {
3666 checkForDeviceAndOutputChanges();
3667 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003668 }
3669 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003670}
3671
3672status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3673{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003674 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003675 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003676 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003677 sp<HwModule> rSubmixModule;
3678 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003679 for (const auto& mix : mixes) {
3680 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003681
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003682 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003683 rSubmixModule = mHwModules.getModuleFromName(
3684 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3685 if (rSubmixModule == 0) {
3686 res = INVALID_OPERATION;
3687 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003688 }
3689 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003690
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003691 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003692
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003693 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003694 res = INVALID_OPERATION;
3695 continue;
3696 }
3697
Kevin Rocard04ed0462019-05-02 17:53:24 -07003698 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3699 if (getDeviceConnectionState(device, address.string()) ==
3700 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3701 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3702 address.string(), "remote-submix",
3703 AUDIO_FORMAT_DEFAULT);
3704 if (res != OK) {
3705 ALOGE("Error making RemoteSubmix device unavailable for mix "
3706 "with type %d, address %s", device, address.string());
3707 }
3708 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003709 }
jiabin5740f082019-08-19 15:08:30 -07003710 rSubmixModule->removeOutputProfile(address.c_str());
3711 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003712
Kevin Rocard153f92d2018-12-18 18:33:28 -08003713 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003714 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003715 res = INVALID_OPERATION;
3716 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003717 } else {
3718 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003719 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003720 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003721 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003722 if (res == NO_ERROR && checkOutputs) {
3723 checkForDeviceAndOutputChanges();
3724 updateCallAndOutputRouting();
3725 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003726 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003727}
3728
Mikhail Naganov100f0122018-11-29 11:22:16 -08003729void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3730{
3731 size_t i = 0;
3732 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3733 for (const auto& fmt : mManualSurroundFormats) {
3734 if (i++ != 0) dst->append(", ");
3735 std::string sfmt;
3736 FormatConverter::toString(fmt, sfmt);
3737 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3738 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3739 }
3740}
3741
Eric Laurentc529cf62020-04-17 18:19:10 -07003742// Returns true if all devices types match the predicate and are supported by one HW module
3743bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003744 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003745 std::function<bool(audio_devices_t)> predicate,
3746 const char *context) {
3747 for (size_t i = 0; i < devices.size(); i++) {
3748 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003749 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003750 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003751 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003752 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003753 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003754 return false;
3755 }
3756 }
3757 return true;
3758}
3759
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003760status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003761 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003762 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003763 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3764 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003765 }
3766 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003767 if (res != NO_ERROR) {
3768 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3769 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003770 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003771
3772 checkForDeviceAndOutputChanges();
3773 updateCallAndOutputRouting();
3774
3775 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003776}
3777
3778status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3779 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003780 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3781 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003782 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003783 __FUNCTION__, uid);
3784 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003785 }
3786
Eric Laurentc529cf62020-04-17 18:19:10 -07003787 checkForDeviceAndOutputChanges();
3788 updateCallAndOutputRouting();
3789
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003790 return res;
3791}
3792
Eric Laurent2517af32020-11-25 15:31:27 +01003793
jiabin0a488932020-08-07 17:32:40 -07003794status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3795 device_role_t role,
3796 const AudioDeviceTypeAddrVector &devices) {
3797 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3798 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003799
Eric Laurentc529cf62020-04-17 18:19:10 -07003800 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003801 return BAD_VALUE;
3802 }
jiabin0a488932020-08-07 17:32:40 -07003803 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003804 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003805 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3806 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003807 return status;
3808 }
3809
3810 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003811
3812 bool forceVolumeReeval = false;
3813 // FIXME: workaround for truncated touch sounds
3814 // to be removed when the problem is handled by system UI
3815 uint32_t delayMs = 0;
3816 if (strategy == mCommunnicationStrategy) {
3817 forceVolumeReeval = true;
3818 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3819 updateInputRouting();
3820 }
3821 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003822
3823 return NO_ERROR;
3824}
3825
3826void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3827{
3828 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003829 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003830 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003831 // Only apply special touch sound delay once
3832 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003833 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003834 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003835 for (size_t i = 0; i < mOutputs.size(); i++) {
3836 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3837 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003838 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3839 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003840 // As done in setDeviceConnectionState, we could also fix default device issue by
3841 // preventing the force re-routing in case of default dev that distinguishes on address.
3842 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003843 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003844 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3845 // If the device is using preferred mixer attributes, the output need to reopen
3846 // with default configuration when the new selected devices are different from
3847 // current routing devices.
3848 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3849 continue;
3850 }
Francois Gaffie601801d2021-06-22 13:27:39 +02003851 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3852 true /*requiresMuteCheck*/,
3853 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003854 // Only apply special touch sound delay once
3855 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003856 }
3857 if (forceVolumeReeval && !newDevices.isEmpty()) {
3858 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3859 }
3860 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003861 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01003862 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003863}
3864
Eric Laurent2517af32020-11-25 15:31:27 +01003865void AudioPolicyManager::updateInputRouting() {
3866 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303867 // Skip for hotword recording as the input device switch
3868 // is handled within sound trigger HAL
3869 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3870 continue;
3871 }
Eric Laurent2517af32020-11-25 15:31:27 +01003872 auto newDevice = getNewInputDevice(activeDesc);
3873 // Force new input selection if the new device can not be reached via current input
3874 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3875 setInputDevice(activeDesc->mIoHandle, newDevice);
3876 } else {
3877 closeInput(activeDesc->mIoHandle);
3878 }
3879 }
3880}
3881
Paul Wang5d7cdb52022-11-22 09:45:06 +00003882status_t
3883AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3884 device_role_t role,
3885 const AudioDeviceTypeAddrVector &devices) {
3886 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3887 dumpAudioDeviceTypeAddrVector(devices).c_str());
3888
3889 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3890 return BAD_VALUE;
3891 }
3892 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
3893 if (status != NO_ERROR) {
3894 ALOGW("Engine could not remove devices %s for strategy %d role %d",
3895 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
3896 return status;
3897 }
3898
3899 checkForDeviceAndOutputChanges();
3900
3901 bool forceVolumeReeval = false;
3902 // TODO(b/263479999): workaround for truncated touch sounds
3903 // to be removed when the problem is handled by system UI
3904 uint32_t delayMs = 0;
3905 if (strategy == mCommunnicationStrategy) {
3906 forceVolumeReeval = true;
3907 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3908 updateInputRouting();
3909 }
3910 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
3911
3912 return NO_ERROR;
3913}
3914
3915status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
3916 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003917{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003918 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003919
Paul Wang5d7cdb52022-11-22 09:45:06 +00003920 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003921 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01003922 ALOGW_IF(status != NAME_NOT_FOUND,
3923 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01003924 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003925 return status;
3926 }
3927
3928 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003929
3930 bool forceVolumeReeval = false;
3931 // FIXME: workaround for truncated touch sounds
3932 // to be removed when the problem is handled by system UI
3933 uint32_t delayMs = 0;
3934 if (strategy == mCommunnicationStrategy) {
3935 forceVolumeReeval = true;
3936 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3937 updateInputRouting();
3938 }
3939 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003940
3941 return NO_ERROR;
3942}
3943
jiabin0a488932020-08-07 17:32:40 -07003944status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3945 device_role_t role,
3946 AudioDeviceTypeAddrVector &devices) {
3947 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003948}
3949
Jiabin Huang3b98d322020-09-03 17:54:16 +00003950status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3951 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3952 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3953 dumpAudioDeviceTypeAddrVector(devices).c_str());
3954
Mikhail Naganov55773032020-10-01 15:08:13 -07003955 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003956 return BAD_VALUE;
3957 }
3958 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3959 ALOGW_IF(status != NO_ERROR,
3960 "Engine could not set preferred devices %s for audio source %d role %d",
3961 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3962
3963 return status;
3964}
3965
3966status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3967 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3968 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3969 dumpAudioDeviceTypeAddrVector(devices).c_str());
3970
Mikhail Naganov55773032020-10-01 15:08:13 -07003971 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003972 return BAD_VALUE;
3973 }
3974 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3975 ALOGW_IF(status != NO_ERROR,
3976 "Engine could not add preferred devices %s for audio source %d role %d",
3977 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3978
Eric Laurent2517af32020-11-25 15:31:27 +01003979 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003980 return status;
3981}
3982
3983status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3984 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3985{
3986 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3987 dumpAudioDeviceTypeAddrVector(devices).c_str());
3988
Mikhail Naganov55773032020-10-01 15:08:13 -07003989 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003990 return BAD_VALUE;
3991 }
3992
3993 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3994 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01003995 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00003996 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01003997 if (status == NO_ERROR) {
3998 updateInputRouting();
3999 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004000 return status;
4001}
4002
4003status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4004 device_role_t role) {
4005 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4006
4007 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004008 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004009 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004010 if (status == NO_ERROR) {
4011 updateInputRouting();
4012 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004013 return status;
4014}
4015
4016status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4017 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4018 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4019}
4020
Oscar Azucena90e77632019-11-27 17:12:28 -08004021status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004022 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004023 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004024 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4025 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004026 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004027 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4028 if (status != NO_ERROR) {
4029 ALOGE("%s() could not set device affinity for userId %d",
4030 __FUNCTION__, userId);
4031 return status;
4032 }
4033
4034 // reevaluate outputs for all devices
4035 checkForDeviceAndOutputChanges();
4036 updateCallAndOutputRouting();
4037
4038 return NO_ERROR;
4039}
4040
4041status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004042 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08004043 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4044 if (status != NO_ERROR) {
4045 ALOGE("%s() Could not remove all device affinities fo 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
Andy Hungc29d82b2018-10-05 12:23:17 -07004057void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004058{
Andy Hungc29d82b2018-10-05 12:23:17 -07004059 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004060 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004061 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004062 std::string stateLiteral;
4063 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004064 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004065 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4066 "communications", "media", "record", "dock", "system",
4067 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4068 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4069 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004070 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4071 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4072 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4073 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4074 dst->append(" (MANUAL: ");
4075 dumpManualSurroundFormats(dst);
4076 dst->append(")");
4077 }
4078 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004079 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004080 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4081 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004082 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07004083 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01004084
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004085 dst->append("\n");
4086 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4087 dst->append("\n");
4088 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004089 mHwModulesAll.dump(dst);
4090 mOutputs.dump(dst);
4091 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004092 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004093 mAudioPatches.dump(dst);
4094 mPolicyMixes.dump(dst);
4095 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004096
Kevin Rocardb99cc752019-03-21 20:52:24 -07004097 dst->appendFormat(" AllowedCapturePolicies:\n");
4098 for (auto& policy : mAllowedCapturePolicies) {
4099 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4100 }
4101
jiabina84c3d32022-12-02 18:59:55 +00004102 dst->appendFormat(" Preferred mixer audio configuration:\n");
4103 for (const auto it : mPreferredMixerAttrInfos) {
4104 dst->appendFormat(" - device port id: %d\n", it.first);
4105 for (const auto preferredMixerInfoIt : it.second) {
4106 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4107 preferredMixerInfoIt.second->dump(dst);
4108 }
4109 }
4110
François Gaffiec005e562018-11-06 15:04:49 +01004111 dst->appendFormat("\nPolicy Engine dump:\n");
4112 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004113}
4114
4115status_t AudioPolicyManager::dump(int fd)
4116{
4117 String8 result;
4118 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07004119 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004120 return NO_ERROR;
4121}
4122
Kevin Rocardb99cc752019-03-21 20:52:24 -07004123status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4124{
4125 mAllowedCapturePolicies[uid] = capturePolicy;
4126 return NO_ERROR;
4127}
4128
Eric Laurente552edb2014-03-10 17:42:56 -07004129// This function checks for the parameters which can be offloaded.
4130// This can be enhanced depending on the capability of the DSP and policy
4131// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004132audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004133{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004134 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004135 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004136 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004137 offloadInfo.format,
4138 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4139 offloadInfo.has_video);
4140
jiabin2b9d5a12021-12-10 01:06:29 +00004141 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004142 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004143 }
4144
4145 // See if there is a profile to support this.
4146 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004147 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004148 offloadInfo.sample_rate,
4149 offloadInfo.format,
4150 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004151 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4152 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004153 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4154 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4155 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004156 if (profile == nullptr) {
4157 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4158 }
4159 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4160 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4161 }
4162 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004163}
4164
Michael Chana94fbb22018-04-24 14:31:19 +10004165bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4166 const audio_attributes_t& attributes) {
4167 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004168 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004169 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4170 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004171 config.sample_rate,
4172 config.format,
4173 config.channel_mask,
4174 output_flags,
4175 true /* directOnly */);
4176 ALOGV("%s() profile %sfound with name: %s, "
4177 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4178 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004179 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004180 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004181
4182 // also try the MSD module if compatible profile not found
4183 if (profile == nullptr) {
4184 profile = getMsdProfileForOutput(outputDevices,
4185 config.sample_rate,
4186 config.format,
4187 config.channel_mask,
4188 output_flags,
4189 true /* directOnly */);
4190 ALOGV("%s() MSD profile %sfound with name: %s, "
4191 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4192 __FUNCTION__, profile != 0 ? "" : "NOT ",
4193 (profile != 0 ? profile->getTagName().c_str() : "null"),
4194 config.sample_rate, config.format, config.channel_mask, output_flags);
4195 }
4196 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004197}
4198
jiabin2b9d5a12021-12-10 01:06:29 +00004199bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4200 bool durationIgnored) {
4201 if (mMasterMono) {
4202 return false; // no offloading if mono is set.
4203 }
4204
4205 // Check if offload has been disabled
4206 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4207 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4208 return false;
4209 }
4210
4211 // Check if stream type is music, then only allow offload as of now.
4212 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4213 {
4214 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4215 return false;
4216 }
4217
4218 //TODO: enable audio offloading with video when ready
4219 const bool allowOffloadWithVideo =
4220 property_get_bool("audio.offload.video", false /* default_value */);
4221 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4222 ALOGV("%s: has_video == true, returning false", __func__);
4223 return false;
4224 }
4225
4226 //If duration is less than minimum value defined in property, return false
4227 const int min_duration_secs = property_get_int32(
4228 "audio.offload.min.duration.secs", -1 /* default_value */);
4229 if (!durationIgnored) {
4230 if (min_duration_secs >= 0) {
4231 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4232 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4233 __func__, min_duration_secs);
4234 return false;
4235 }
4236 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4237 ALOGV("%s: Offload denied by duration < default min(=%u)",
4238 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4239 return false;
4240 }
4241 }
4242
4243 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4244 // creating an offloaded track and tearing it down immediately after start when audioflinger
4245 // detects there is an active non offloadable effect.
4246 // FIXME: We should check the audio session here but we do not have it in this context.
4247 // This may prevent offloading in rare situations where effects are left active by apps
4248 // in the background.
4249 if (mEffects.isNonOffloadableEffectEnabled()) {
4250 return false;
4251 }
4252
4253 return true;
4254}
4255
4256audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4257 const audio_config_t *config) {
4258 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4259 offloadInfo.format = config->format;
4260 offloadInfo.sample_rate = config->sample_rate;
4261 offloadInfo.channel_mask = config->channel_mask;
4262 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4263 offloadInfo.has_video = false;
4264 offloadInfo.is_streaming = false;
4265 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4266
4267 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4268 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4269 audio_flags_to_audio_output_flags(attr->flags, &flags);
4270 // only retain flags that will drive compressed offload or passthrough
4271 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4272 if (offloadPossible) {
4273 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4274 }
4275 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4276
Dorin Drimusfae3c642022-03-17 18:36:30 +01004277 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004278 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004279 DeviceVector outputDevices = engineOutputDevices;
4280 // the MSD module checks for different conditions and output devices
4281 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4282 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4283 continue;
4284 }
4285 outputDevices = getMsdAudioOutDevices();
4286 }
jiabin2b9d5a12021-12-10 01:06:29 +00004287 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004288 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004289 config->sample_rate, nullptr /*updatedSamplingRate*/,
4290 config->format, nullptr /*updatedFormat*/,
4291 config->channel_mask, nullptr /*updatedChannelMask*/,
4292 flags)) {
4293 continue;
4294 }
4295 // reject profiles not corresponding to a device currently available
4296 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4297 continue;
4298 }
4299 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4300 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004301 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004302 != AUDIO_DIRECT_NOT_SUPPORTED) {
4303 // Already reports offload gapless supported. No need to report offload support.
4304 continue;
4305 }
4306 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4307 != AUDIO_OUTPUT_FLAG_NONE) {
4308 // If offload gapless is reported, no need to report offload support.
4309 directMode = (audio_direct_mode_t) ((directMode &
4310 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4311 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4312 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004313 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004314 }
4315 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004316 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004317 }
4318 }
4319 }
4320 return directMode;
4321}
4322
Dorin Drimusf2196d82022-01-03 12:11:18 +01004323status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4324 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004325 if (mEffects.isNonOffloadableEffectEnabled()) {
4326 return OK;
4327 }
jiabinf1c73972022-04-14 16:28:52 -07004328 DeviceVector devices;
4329 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004330 if (status != OK) {
4331 return status;
4332 }
4333 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4334 if (devices.empty()) {
4335 return OK; // no output devices for the attributes
4336 }
jiabinf1c73972022-04-14 16:28:52 -07004337 return getProfilesForDevices(devices, audioProfilesVector,
4338 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004339}
4340
jiabina84c3d32022-12-02 18:59:55 +00004341status_t AudioPolicyManager::getSupportedMixerAttributes(
4342 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4343 ALOGV("%s, portId=%d", __func__, portId);
4344 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4345 if (deviceDescriptor == nullptr) {
4346 ALOGE("%s the requested device is currently unavailable", __func__);
4347 return BAD_VALUE;
4348 }
4349 for (const auto& hwModule : mHwModules) {
4350 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4351 if (curProfile->supportsDevice(deviceDescriptor)) {
4352 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4353 }
4354 }
4355 }
4356 return NO_ERROR;
4357}
4358
4359status_t AudioPolicyManager::setPreferredMixerAttributes(
4360 const audio_attributes_t *attr,
4361 audio_port_handle_t portId,
4362 uid_t uid,
4363 const audio_mixer_attributes_t *mixerAttributes) {
4364 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4365 "mixerBehavior=%d}, uid=%d, portId=%u",
4366 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4367 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4368 mixerAttributes->mixer_behavior, uid, portId);
4369 if (attr->usage != AUDIO_USAGE_MEDIA) {
4370 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4371 return BAD_VALUE;
4372 }
4373 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4374 if (deviceDescriptor == nullptr) {
4375 ALOGE("%s the requested device is currently unavailable", __func__);
4376 return BAD_VALUE;
4377 }
4378 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4379 ALOGE("%s(%d), type=%d, is not a usb output device",
4380 __func__, portId, deviceDescriptor->type());
4381 return BAD_VALUE;
4382 }
4383
4384 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4385 audio_flags_to_audio_output_flags(attr->flags, &flags);
4386 flags = (audio_output_flags_t) (flags |
4387 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4388 sp<IOProfile> profile = nullptr;
4389 DeviceVector devices(deviceDescriptor);
4390 for (const auto& hwModule : mHwModules) {
4391 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4392 if (curProfile->hasDynamicAudioProfile()
4393 && curProfile->isCompatibleProfile(devices,
4394 mixerAttributes->config.sample_rate,
4395 nullptr /*updatedSamplingRate*/,
4396 mixerAttributes->config.format,
4397 nullptr /*updatedFormat*/,
4398 mixerAttributes->config.channel_mask,
4399 nullptr /*updatedChannelMask*/,
4400 flags,
4401 false /*exactMatchRequiredForInputFlags*/)) {
4402 profile = curProfile;
4403 break;
4404 }
4405 }
4406 }
4407 if (profile == nullptr) {
4408 ALOGE("%s, there is no compatible profile found", __func__);
4409 return BAD_VALUE;
4410 }
4411
4412 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4413 sp<PreferredMixerAttributesInfo>::make(
4414 uid, portId, profile, flags, *mixerAttributes);
4415 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4416 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4417
4418 // If 1) there is any client from the preferred mixer configuration owner that is currently
4419 // active and matches the strategy and 2) current output is on the preferred device and the
4420 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4421 // configuration.
4422 std::vector<audio_io_handle_t> outputsToReopen;
4423 for (size_t i = 0; i < mOutputs.size(); i++) {
4424 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004425 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4426 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4427 output->mUsePreferredMixerAttributes = true;
4428 } else {
4429 for (const auto &client: output->getActiveClients()) {
4430 if (client->uid() == uid && client->strategy() == strategy) {
4431 client->setIsInvalid();
4432 outputsToReopen.push_back(output->mIoHandle);
4433 }
jiabina84c3d32022-12-02 18:59:55 +00004434 }
4435 }
4436 }
4437 }
4438 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4439 config.sample_rate = mixerAttributes->config.sample_rate;
4440 config.channel_mask = mixerAttributes->config.channel_mask;
4441 config.format = mixerAttributes->config.format;
4442 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004443 sp<SwAudioOutputDescriptor> desc =
4444 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4445 if (desc == nullptr) {
4446 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4447 continue;
4448 }
4449 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004450 }
4451
4452 return NO_ERROR;
4453}
4454
4455sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
4456 audio_port_handle_t devicePortId, product_strategy_t strategy) {
4457 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4458 if (it == mPreferredMixerAttrInfos.end()) {
4459 return nullptr;
4460 }
4461 auto mixerAttrInfoIt = it->second.find(strategy);
4462 if (mixerAttrInfoIt == it->second.end()) {
4463 return nullptr;
4464 }
4465 return mixerAttrInfoIt->second;
4466}
4467
4468status_t AudioPolicyManager::getPreferredMixerAttributes(
4469 const audio_attributes_t *attr,
4470 audio_port_handle_t portId,
4471 audio_mixer_attributes_t* mixerAttributes) {
4472 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4473 portId, mEngine->getProductStrategyForAttributes(*attr));
4474 if (info == nullptr) {
4475 return NAME_NOT_FOUND;
4476 }
4477 *mixerAttributes = info->getMixerAttributes();
4478 return NO_ERROR;
4479}
4480
4481status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4482 audio_port_handle_t portId,
4483 uid_t uid) {
4484 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4485 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4486 if (preferredMixerAttrInfo == nullptr) {
4487 return NAME_NOT_FOUND;
4488 }
4489 if (preferredMixerAttrInfo->getUid() != uid) {
4490 ALOGE("%s, requested uid=%d, owned uid=%d",
4491 __func__, uid, preferredMixerAttrInfo->getUid());
4492 return PERMISSION_DENIED;
4493 }
4494 mPreferredMixerAttrInfos[portId].erase(strategy);
4495 if (mPreferredMixerAttrInfos[portId].empty()) {
4496 mPreferredMixerAttrInfos.erase(portId);
4497 }
4498
4499 // Reconfig existing output
4500 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4501 for (size_t i = 0; i < mOutputs.size(); i++) {
4502 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4503 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4504 }
4505 }
4506 for (const auto output : potentialOutputsToReopen) {
4507 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4508 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4509 preferredMixerAttrInfo->getFlags())) {
4510 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4511 }
4512 }
4513 return NO_ERROR;
4514}
4515
Eric Laurent6a94d692014-05-20 11:18:06 -07004516status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4517 audio_port_type_t type,
4518 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004519 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004520 unsigned int *generation)
4521{
jiabin19cdba52020-11-24 11:28:58 -08004522 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4523 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004524 return BAD_VALUE;
4525 }
4526 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004527 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004528 *num_ports = 0;
4529 }
4530
4531 size_t portsWritten = 0;
4532 size_t portsMax = *num_ports;
4533 *num_ports = 0;
4534 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004535 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4536 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004537 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004538 for (const auto& dev : mAvailableOutputDevices) {
4539 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004540 continue;
4541 }
4542 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004543 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004544 }
4545 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004546 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004547 }
4548 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004549 for (const auto& dev : mAvailableInputDevices) {
4550 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004551 continue;
4552 }
4553 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004554 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004555 }
4556 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004557 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004558 }
4559 }
4560 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4561 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4562 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4563 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4564 }
4565 *num_ports += mInputs.size();
4566 }
4567 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004568 size_t numOutputs = 0;
4569 for (size_t i = 0; i < mOutputs.size(); i++) {
4570 if (!mOutputs[i]->isDuplicated()) {
4571 numOutputs++;
4572 if (portsWritten < portsMax) {
4573 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4574 }
4575 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004576 }
Eric Laurent84c70242014-06-23 08:46:27 -07004577 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004578 }
4579 }
jiabina84c3d32022-12-02 18:59:55 +00004580
Eric Laurent6a94d692014-05-20 11:18:06 -07004581 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004582 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004583 return NO_ERROR;
4584}
4585
jiabin19cdba52020-11-24 11:28:58 -08004586status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004587{
Eric Laurent99fcae42018-05-17 16:59:18 -07004588 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4589 return BAD_VALUE;
4590 }
4591 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4592 if (dev != 0) {
4593 dev->toAudioPort(port);
4594 return NO_ERROR;
4595 }
4596 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4597 if (dev != 0) {
4598 dev->toAudioPort(port);
4599 return NO_ERROR;
4600 }
4601 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4602 if (out != 0) {
4603 out->toAudioPort(port);
4604 return NO_ERROR;
4605 }
4606 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4607 if (in != 0) {
4608 in->toAudioPort(port);
4609 return NO_ERROR;
4610 }
4611 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004612}
4613
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004614status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4615 audio_patch_handle_t *handle,
4616 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004617{
François Gaffieafd4cea2019-11-18 15:50:22 +01004618 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004619 if (handle == NULL || patch == NULL) {
4620 return BAD_VALUE;
4621 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004622 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004623 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004624 return BAD_VALUE;
4625 }
4626 // only one source per audio patch supported for now
4627 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004628 return INVALID_OPERATION;
4629 }
Eric Laurent874c42872014-08-08 15:13:39 -07004630 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004631 return INVALID_OPERATION;
4632 }
Eric Laurent874c42872014-08-08 15:13:39 -07004633 for (size_t i = 0; i < patch->num_sinks; i++) {
4634 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4635 return INVALID_OPERATION;
4636 }
4637 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004638
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004639 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4640 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4641 if (srcDevice == nullptr || sinkDevice == nullptr) {
4642 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4643 return BAD_VALUE;
4644 }
4645 ALOGV("%s between source %s and sink %s", __func__,
4646 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4647 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4648 // Default attributes, default volume priority, not to infer with non raw audio patches.
4649 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4650 const struct audio_port_config *source = &patch->sources[0];
4651 sp<SourceClientDescriptor> sourceDesc =
4652 new InternalSourceClientDescriptor(
4653 portId, uid, attributes, *source, srcDevice, sinkDevice,
4654 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4655
4656 status_t status =
4657 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4658
4659 if (status != NO_ERROR) {
4660 return INVALID_OPERATION;
4661 }
4662 mAudioSources.add(portId, sourceDesc);
4663 return NO_ERROR;
4664}
4665
4666status_t AudioPolicyManager::connectAudioSourceToSink(
4667 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4668 const struct audio_patch *patch,
4669 audio_patch_handle_t &handle,
4670 uid_t uid, uint32_t delayMs)
4671{
4672 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4673 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4674 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4675 return INVALID_OPERATION;
4676 }
4677 sourceDesc->connect(handle, sinkDevice);
4678 if (isMsdPatch(handle)) {
4679 return NO_ERROR;
4680 }
4681 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4682 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4683 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4684 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4685 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4686 goto FailurePatchAdded;
4687 }
4688 status = swOutput->start();
4689 if (status != NO_ERROR) {
4690 goto FailureSourceAdded;
4691 }
4692 swOutput->addClient(sourceDesc);
4693 status = startSource(swOutput, sourceDesc, &delayMs);
4694 if (status != NO_ERROR) {
4695 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4696 goto FailureSourceActive;
4697 }
4698 if (delayMs != 0) {
4699 usleep(delayMs * 1000);
4700 }
4701 return NO_ERROR;
4702
4703FailureSourceActive:
4704 swOutput->stop();
4705 releaseOutput(sourceDesc->portId());
4706FailureSourceAdded:
4707 sourceDesc->setSwOutput(nullptr);
4708FailurePatchAdded:
4709 releaseAudioPatchInternal(handle);
4710 return INVALID_OPERATION;
4711}
4712
4713status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4714 audio_patch_handle_t *handle,
4715 uid_t uid, uint32_t delayMs,
4716 const sp<SourceClientDescriptor>& sourceDesc)
4717{
4718 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004719 sp<AudioPatch> patchDesc;
4720 ssize_t index = mAudioPatches.indexOfKey(*handle);
4721
François Gaffieafd4cea2019-11-18 15:50:22 +01004722 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4723 patch->sources[0].role,
4724 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004725#if LOG_NDEBUG == 0
4726 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004727 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4728 patch->sinks[i].role,
4729 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004730 }
4731#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004732
4733 if (index >= 0) {
4734 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004735 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4736 __func__, mUidCached, patchDesc->getUid(), uid);
4737 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004738 return INVALID_OPERATION;
4739 }
4740 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004741 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004742 }
4743
4744 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004745 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004746 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004747 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004748 return BAD_VALUE;
4749 }
Eric Laurent84c70242014-06-23 08:46:27 -07004750 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4751 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004752 if (patchDesc != 0) {
4753 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004754 ALOGV("%s source id differs for patch current id %d new id %d",
4755 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004756 return BAD_VALUE;
4757 }
4758 }
Eric Laurent874c42872014-08-08 15:13:39 -07004759 DeviceVector devices;
4760 for (size_t i = 0; i < patch->num_sinks; i++) {
4761 // Only support mix to devices connection
4762 // TODO add support for mix to mix connection
4763 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004764 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004765 return INVALID_OPERATION;
4766 }
4767 sp<DeviceDescriptor> devDesc =
4768 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4769 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004770 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004771 return BAD_VALUE;
4772 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004773
François Gaffie11d30102018-11-02 16:09:09 +01004774 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004775 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004776 NULL, // updatedSamplingRate
4777 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004778 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004779 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004780 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004781 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004782 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004783 return INVALID_OPERATION;
4784 }
4785 devices.add(devDesc);
4786 }
4787 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004788 return INVALID_OPERATION;
4789 }
Eric Laurent874c42872014-08-08 15:13:39 -07004790
Eric Laurent6a94d692014-05-20 11:18:06 -07004791 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004792 ALOGV("%s setting device %s on output %d",
4793 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004794 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004795 index = mAudioPatches.indexOfKey(*handle);
4796 if (index >= 0) {
4797 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004798 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004799 }
4800 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004801 patchDesc->setUid(uid);
4802 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004803 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004804 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004805 return INVALID_OPERATION;
4806 }
4807 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4808 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4809 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004810 // only one sink supported when connecting an input device to a mix
4811 if (patch->num_sinks > 1) {
4812 return INVALID_OPERATION;
4813 }
François Gaffie53615e22015-03-19 09:24:12 +01004814 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004815 if (inputDesc == NULL) {
4816 return BAD_VALUE;
4817 }
4818 if (patchDesc != 0) {
4819 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4820 return BAD_VALUE;
4821 }
4822 }
François Gaffie11d30102018-11-02 16:09:09 +01004823 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004824 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004825 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004826 return BAD_VALUE;
4827 }
4828
François Gaffie11d30102018-11-02 16:09:09 +01004829 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004830 patch->sinks[0].sample_rate,
4831 NULL, /*updatedSampleRate*/
4832 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004833 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004834 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004835 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004836 // FIXME for the parameter type,
4837 // and the NONE
4838 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004839 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004840 return INVALID_OPERATION;
4841 }
4842 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004843 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004844 device->toString().c_str(), inputDesc->mIoHandle);
4845 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004846 index = mAudioPatches.indexOfKey(*handle);
4847 if (index >= 0) {
4848 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004849 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004850 }
4851 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004852 patchDesc->setUid(uid);
4853 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004854 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004855 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004856 return INVALID_OPERATION;
4857 }
4858 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4859 // device to device connection
4860 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004861 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004862 return BAD_VALUE;
4863 }
4864 }
François Gaffie11d30102018-11-02 16:09:09 +01004865 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004866 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004867 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004868 return BAD_VALUE;
4869 }
Eric Laurent874c42872014-08-08 15:13:39 -07004870
Eric Laurent6a94d692014-05-20 11:18:06 -07004871 //update source and sink with our own data as the data passed in the patch may
4872 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004873 PatchBuilder patchBuilder;
4874 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004875
4876 // if first sink is to MSD, establish single MSD patch
4877 if (getMsdAudioOutDevices().contains(
4878 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4879 ALOGV("%s patching to MSD", __FUNCTION__);
4880 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4881 goto installPatch;
4882 }
4883
François Gaffieafd4cea2019-11-18 15:50:22 +01004884 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4885 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004886
Eric Laurent874c42872014-08-08 15:13:39 -07004887 for (size_t i = 0; i < patch->num_sinks; i++) {
4888 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004889 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004890 return INVALID_OPERATION;
4891 }
François Gaffie11d30102018-11-02 16:09:09 +01004892 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004893 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004894 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004895 return BAD_VALUE;
4896 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004897 audio_port_config sinkPortConfig = {};
4898 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4899 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004900
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004901 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4902 // volume management purpose (tracking activity)
4903 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4904 // in config XML to reach the sink so that is can be declared as available.
4905 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004906 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004907 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004908 // take care of dynamic routing for SwOutput selection,
4909 audio_attributes_t attributes = sourceDesc->attributes();
4910 audio_stream_type_t stream = sourceDesc->stream();
4911 audio_attributes_t resultAttr;
4912 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4913 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02004914 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
4915 config.channel_mask =
4916 (audio_channel_mask_get_representation(sourceMask)
4917 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
4918 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004919 config.format = sourceDesc->config().format;
4920 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4921 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4922 bool isRequestedDeviceForExclusiveUse = false;
4923 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004924 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00004925 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004926 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4927 &stream, sourceDesc->uid(), &config, &flags,
4928 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00004929 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004930 if (output == AUDIO_IO_HANDLE_NONE) {
4931 ALOGV("%s no output for device %s",
4932 __FUNCTION__, sinkDevice->toString().c_str());
4933 return INVALID_OPERATION;
4934 }
4935 outputDesc = mOutputs.valueFor(output);
4936 if (outputDesc->isDuplicated()) {
4937 ALOGE("%s output is duplicated", __func__);
4938 return INVALID_OPERATION;
4939 }
François Gaffie7e39df22022-04-26 12:48:49 +02004940 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4941 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004942 } else {
4943 // Same for "raw patches" aka created from createAudioPatch API
4944 SortedVector<audio_io_handle_t> outputs =
4945 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4946 // if the sink device is reachable via an opened output stream, request to
4947 // go via this output stream by adding a second source to the patch
4948 // description
4949 output = selectOutput(outputs);
4950 if (output == AUDIO_IO_HANDLE_NONE) {
4951 ALOGE("%s no output available for internal patch sink", __func__);
4952 return INVALID_OPERATION;
4953 }
4954 outputDesc = mOutputs.valueFor(output);
4955 if (outputDesc->isDuplicated()) {
4956 ALOGV("%s output for device %s is duplicated",
4957 __func__, sinkDevice->toString().c_str());
4958 return INVALID_OPERATION;
4959 }
François Gaffie7e39df22022-04-26 12:48:49 +02004960 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004961 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004962 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004963 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004964 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004965 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004966 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4967 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004968 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4969 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004970 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004971 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004972 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004973 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004974 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004975 return INVALID_OPERATION;
4976 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004977 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004978 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004979 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004980 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004981 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02004982 srcMixPortConfig.ext.mix.usecase.stream =
4983 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004984 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4985 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004986 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004987 }
Eric Laurent83b88082014-06-20 18:31:16 -07004988 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004989 }
4990 // TODO: check from routing capabilities in config file and other conflicting patches
4991
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004992installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004993 status_t status = installPatch(
4994 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004995 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004996 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004997 return INVALID_OPERATION;
4998 }
4999 } else {
5000 return BAD_VALUE;
5001 }
5002 } else {
5003 return BAD_VALUE;
5004 }
5005 return NO_ERROR;
5006}
5007
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005008status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005009{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005010 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005011 ssize_t index = mAudioPatches.indexOfKey(handle);
5012
5013 if (index < 0) {
5014 return BAD_VALUE;
5015 }
5016 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005017 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5018 __func__, mUidCached, patchDesc->getUid(), uid);
5019 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005020 return INVALID_OPERATION;
5021 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005022 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5023 for (size_t i = 0; i < mAudioSources.size(); i++) {
5024 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5025 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5026 portId = sourceDesc->portId();
5027 break;
5028 }
5029 }
5030 return portId != AUDIO_PORT_HANDLE_NONE ?
5031 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005032}
Eric Laurent6a94d692014-05-20 11:18:06 -07005033
François Gaffieafd4cea2019-11-18 15:50:22 +01005034status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005035 uint32_t delayMs,
5036 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005037{
5038 ALOGV("%s patch %d", __func__, handle);
5039 if (mAudioPatches.indexOfKey(handle) < 0) {
5040 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5041 return BAD_VALUE;
5042 }
5043 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005044 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005045 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005046 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005047 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005048 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005049 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005050 return BAD_VALUE;
5051 }
5052
François Gaffie11d30102018-11-02 16:09:09 +01005053 setOutputDevices(outputDesc,
5054 getNewOutputDevices(outputDesc, true /*fromCache*/),
5055 true,
5056 0,
5057 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005058 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5059 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005060 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005061 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005062 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005063 return BAD_VALUE;
5064 }
5065 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005066 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005067 true,
5068 NULL);
5069 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005070 status_t status =
5071 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5072 ALOGV("%s patch panel returned %d patchHandle %d",
5073 __func__, status, patchDesc->getAfHandle());
5074 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005075 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005076 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005077 // SW or HW Bridge
5078 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5079 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005080 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005081 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5082 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5083 outputDesc = sourceDesc->swOutput().promote();
5084 }
5085 if (outputDesc == nullptr) {
5086 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5087 // releaseOutput has already called closeOutput in case of direct output
5088 return NO_ERROR;
5089 }
François Gaffie7e39df22022-04-26 12:48:49 +02005090 patchHandle = outputDesc->getPatchHandle();
5091 // When a Sw bridge is released, the mixer used by this bridge will release its
5092 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
5093 // Reuse patch handle to force audio flinger removing initial mixer patch removal
5094 // updating hal patch handle (prevent leaks).
5095 // While using a HwBridge, force reconsidering device only if not reusing an existing
5096 // output and no more activity on output (will force to close).
5097 bool force = sourceDesc->useSwBridge() ||
5098 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
5099 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5100 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5101 // Reconsider device only for cases:
5102 // 1 / Active Output
5103 // 2 / Inactive Output previously hosting HwBridge
5104 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5105 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5106 sourceDesc->canCloseOutput();
5107 setOutputDevices(outputDesc,
5108 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5109 outputDesc->devices(),
5110 force,
5111 0,
5112 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005113 } else {
5114 return BAD_VALUE;
5115 }
5116 } else {
5117 return BAD_VALUE;
5118 }
5119 return NO_ERROR;
5120}
5121
5122status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5123 struct audio_patch *patches,
5124 unsigned int *generation)
5125{
François Gaffie53615e22015-03-19 09:24:12 +01005126 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005127 return BAD_VALUE;
5128 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005129 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005130 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005131}
5132
Eric Laurente1715a42014-05-20 11:30:42 -07005133status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005134{
Eric Laurente1715a42014-05-20 11:30:42 -07005135 ALOGV("setAudioPortConfig()");
5136
5137 if (config == NULL) {
5138 return BAD_VALUE;
5139 }
5140 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5141 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005142 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5143 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005144 }
5145
Eric Laurenta121f902014-06-03 13:32:54 -07005146 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005147 if (config->type == AUDIO_PORT_TYPE_MIX) {
5148 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005149 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005150 if (outputDesc == NULL) {
5151 return BAD_VALUE;
5152 }
Eric Laurent84c70242014-06-23 08:46:27 -07005153 ALOG_ASSERT(!outputDesc->isDuplicated(),
5154 "setAudioPortConfig() called on duplicated output %d",
5155 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005156 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005157 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005158 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005159 if (inputDesc == NULL) {
5160 return BAD_VALUE;
5161 }
Eric Laurenta121f902014-06-03 13:32:54 -07005162 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005163 } else {
5164 return BAD_VALUE;
5165 }
5166 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5167 sp<DeviceDescriptor> deviceDesc;
5168 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5169 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5170 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5171 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5172 } else {
5173 return BAD_VALUE;
5174 }
5175 if (deviceDesc == NULL) {
5176 return BAD_VALUE;
5177 }
Eric Laurenta121f902014-06-03 13:32:54 -07005178 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005179 } else {
5180 return BAD_VALUE;
5181 }
5182
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005183 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005184 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5185 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005186 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005187 audioPortConfig->toAudioPortConfig(&newConfig, config);
5188 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005189 }
Eric Laurenta121f902014-06-03 13:32:54 -07005190 if (status != NO_ERROR) {
5191 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005192 }
Eric Laurente1715a42014-05-20 11:30:42 -07005193
5194 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005195}
5196
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005197void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5198{
Eric Laurentd60560a2015-04-10 11:31:20 -07005199 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005200 clearAudioPatches(uid);
5201 clearSessionRoutes(uid);
5202}
5203
Eric Laurent6a94d692014-05-20 11:18:06 -07005204void AudioPolicyManager::clearAudioPatches(uid_t uid)
5205{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005206 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005207 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005208 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005209 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005210 }
5211 }
5212}
5213
François Gaffiec005e562018-11-06 15:04:49 +01005214void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005215{
François Gaffiec005e562018-11-06 15:04:49 +01005216 // Take the first attributes following the product strategy as it is used to retrieve the routed
5217 // device. All attributes wihin a strategy follows the same "routing strategy"
5218 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5219 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005220 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005221 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005222 for (size_t j = 0; j < mOutputs.size(); j++) {
5223 if (mOutputs.keyAt(j) == ouptutToSkip) {
5224 continue;
5225 }
5226 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005227 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005228 continue;
5229 }
5230 // If the default device for this strategy is on another output mix,
5231 // invalidate all tracks in this strategy to force re connection.
5232 // Otherwise select new device on the output mix.
5233 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005234 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005235 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005236 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5237 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5238 // If the device is using preferred mixer attributes, the output need to reopen
5239 // with default configuration when the new selected devices are different from
5240 // current routing devices.
5241 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5242 continue;
5243 }
5244 setOutputDevices(outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005245 }
5246 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005247 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005248}
5249
5250void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5251{
5252 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005253 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005254 for (size_t i = 0; i < mOutputs.size(); i++) {
5255 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005256 for (const auto& client : outputDesc->getClientIterable()) {
5257 if (client->hasPreferredDevice() && client->uid() == uid) {
5258 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005259 auto clientStrategy = client->strategy();
5260 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5261 end(affectedStrategies)) {
5262 continue;
5263 }
5264 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005265 }
5266 }
5267 }
5268 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005269 for (const auto& strategy : affectedStrategies) {
5270 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005271 }
5272
5273 // remove input routes associated with this uid
5274 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005275 for (size_t i = 0; i < mInputs.size(); i++) {
5276 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005277 for (const auto& client : inputDesc->getClientIterable()) {
5278 if (client->hasPreferredDevice() && client->uid() == uid) {
5279 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5280 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005281 }
5282 }
5283 }
5284 // reroute inputs if necessary
5285 SortedVector<audio_io_handle_t> inputsToClose;
5286 for (size_t i = 0; i < mInputs.size(); i++) {
5287 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005288 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005289 inputsToClose.add(inputDesc->mIoHandle);
5290 }
5291 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005292 for (const auto& input : inputsToClose) {
5293 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005294 }
5295}
5296
Eric Laurentd60560a2015-04-10 11:31:20 -07005297void AudioPolicyManager::clearAudioSources(uid_t uid)
5298{
5299 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005300 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5301 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005302 stopAudioSource(mAudioSources.keyAt(i));
5303 }
5304 }
5305}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005306
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005307status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5308 audio_io_handle_t *ioHandle,
5309 audio_devices_t *device)
5310{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005311 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5312 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005313 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01005314 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005315
François Gaffiedf372692015-03-19 10:43:27 +01005316 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005317}
5318
Eric Laurentd60560a2015-04-10 11:31:20 -07005319status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005320 const audio_attributes_t *attributes,
5321 audio_port_handle_t *portId,
5322 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005323{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005324 ALOGV("%s", __FUNCTION__);
5325 *portId = AUDIO_PORT_HANDLE_NONE;
5326
5327 if (source == NULL || attributes == NULL || portId == NULL) {
5328 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5329 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005330 return BAD_VALUE;
5331 }
5332
Eric Laurentd60560a2015-04-10 11:31:20 -07005333 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5334 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005335 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5336 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005337 return INVALID_OPERATION;
5338 }
5339
François Gaffie11d30102018-11-02 16:09:09 +01005340 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005341 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005342 String8(source->ext.device.address),
5343 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005344 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005345 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005346 return BAD_VALUE;
5347 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005348
jiabin4ef93452019-09-10 14:29:54 -07005349 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005350
François Gaffieaaac0fd2018-11-22 17:56:39 +01005351 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005352 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005353 mEngine->getStreamTypeForAttributes(*attributes),
5354 mEngine->getProductStrategyForAttributes(*attributes),
5355 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005356
5357 status_t status = connectAudioSource(sourceDesc);
5358 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005359 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005360 }
5361 return status;
5362}
5363
Francois Gaffie601801d2021-06-22 13:27:39 +02005364sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5365 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5366{
5367 ALOGV("%s", __FUNCTION__);
5368 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5369
5370 status_t status = startAudioSource(source, attributes, &portId, uid);
5371 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5372 return mAudioSources.valueFor(portId);
5373}
5374
5375
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005376status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005377{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005378 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005379
5380 // make sure we only have one patch per source.
5381 disconnectAudioSource(sourceDesc);
5382
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005383 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005384 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5385 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5386 sourceDesc->srcDevice()->type(),
5387 String8(sourceDesc->srcDevice()->address().c_str()),
5388 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005389 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005390 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005391 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005392 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005393 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5394 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5395 return INVALID_OPERATION;
5396 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005397 PatchBuilder patchBuilder;
5398 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5399 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005400
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005401 return connectAudioSourceToSink(
5402 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005403}
5404
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005405status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005406{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005407 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5408 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005409 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005410 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005411 return BAD_VALUE;
5412 }
5413 status_t status = disconnectAudioSource(sourceDesc);
5414
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005415 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005416 return status;
5417}
5418
Andy Hung2ddee192015-12-18 17:34:44 -08005419status_t AudioPolicyManager::setMasterMono(bool mono)
5420{
5421 if (mMasterMono == mono) {
5422 return NO_ERROR;
5423 }
5424 mMasterMono = mono;
5425 // if enabling mono we close all offloaded devices, which will invalidate the
5426 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5427 // for recreating the new AudioTrack as non-offloaded PCM.
5428 //
5429 // If disabling mono, we leave all tracks as is: we don't know which clients
5430 // and tracks are able to be recreated as offloaded. The next "song" should
5431 // play back offloaded.
5432 if (mMasterMono) {
5433 Vector<audio_io_handle_t> offloaded;
5434 for (size_t i = 0; i < mOutputs.size(); ++i) {
5435 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5436 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5437 offloaded.push(desc->mIoHandle);
5438 }
5439 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005440 for (const auto& handle : offloaded) {
5441 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005442 }
5443 }
5444 // update master mono for all remaining outputs
5445 for (size_t i = 0; i < mOutputs.size(); ++i) {
5446 updateMono(mOutputs.keyAt(i));
5447 }
5448 return NO_ERROR;
5449}
5450
5451status_t AudioPolicyManager::getMasterMono(bool *mono)
5452{
5453 *mono = mMasterMono;
5454 return NO_ERROR;
5455}
5456
Eric Laurentac9cef52017-06-09 15:46:26 -07005457float AudioPolicyManager::getStreamVolumeDB(
5458 audio_stream_type_t stream, int index, audio_devices_t device)
5459{
jiabin9a3361e2019-10-01 09:38:30 -07005460 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005461}
5462
jiabin81772902018-04-02 17:52:27 -07005463status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5464 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005465 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005466{
Kriti Dang6537def2021-03-02 13:46:59 +01005467 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5468 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005469 return BAD_VALUE;
5470 }
Kriti Dang6537def2021-03-02 13:46:59 +01005471 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5472 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005473
5474 size_t formatsWritten = 0;
5475 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005476
Kriti Dang6537def2021-03-02 13:46:59 +01005477 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005478 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5479 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005480 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005481 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005482 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005483 bool formatEnabled = true;
5484 switch (forceUse) {
5485 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005486 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005487 break;
5488 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5489 formatEnabled = false;
5490 break;
5491 default: // AUTO or ALWAYS => true
5492 break;
jiabin81772902018-04-02 17:52:27 -07005493 }
5494 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5495 }
jiabin81772902018-04-02 17:52:27 -07005496 }
5497 return NO_ERROR;
5498}
5499
Kriti Dang6537def2021-03-02 13:46:59 +01005500status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5501 audio_format_t *surroundFormats) {
5502 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5503 return BAD_VALUE;
5504 }
5505 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5506 __func__, *numSurroundFormats, surroundFormats);
5507
5508 size_t formatsWritten = 0;
5509 size_t formatsMax = *numSurroundFormats;
5510 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5511
5512 // Return formats from all device profiles that have already been resolved by
5513 // checkOutputsForDevice().
5514 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5515 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5516 audio_devices_t deviceType = device->type();
5517 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5518 // returns formats reported by HDMI devices.
5519 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5520 continue;
5521 }
5522 // Formats reported by sink devices
5523 std::unordered_set<audio_format_t> formatset;
5524 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5525 formatset.insert(it->second.begin(), it->second.end());
5526 }
5527
5528 // Formats hard-coded in the in policy configuration file (if any).
5529 FormatVector encodedFormats = device->encodedFormats();
5530 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5531 // Filter the formats which are supported by the vendor hardware.
5532 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5533 if (mConfig.getSurroundFormats().count(*it) != 0) {
5534 formats.insert(*it);
5535 } else {
5536 for (const auto& pair : mConfig.getSurroundFormats()) {
5537 if (pair.second.count(*it) != 0) {
5538 formats.insert(pair.first);
5539 break;
5540 }
5541 }
5542 }
5543 }
5544 }
5545 *numSurroundFormats = formats.size();
5546 for (const auto& format: formats) {
5547 if (formatsWritten < formatsMax) {
5548 surroundFormats[formatsWritten++] = format;
5549 }
5550 }
5551 return NO_ERROR;
5552}
5553
jiabin81772902018-04-02 17:52:27 -07005554status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5555{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005556 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005557 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5558 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005559 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005560 return BAD_VALUE;
5561 }
5562
Mikhail Naganov100f0122018-11-29 11:22:16 -08005563 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5564 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005565 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005566 return INVALID_OPERATION;
5567 }
5568
Mikhail Naganov100f0122018-11-29 11:22:16 -08005569 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005570 return NO_ERROR;
5571 }
5572
Mikhail Naganov100f0122018-11-29 11:22:16 -08005573 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005574 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005575 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005576 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005577 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005578 }
5579 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005580 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005581 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005582 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005583 }
5584 }
5585
5586 sp<SwAudioOutputDescriptor> outputDesc;
5587 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005588 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5589 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005590 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5591 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005592 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005593 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005594 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5595 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5596 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005597 name.c_str(),
5598 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005599 if (status != NO_ERROR) {
5600 continue;
5601 }
5602 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5603 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5604 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005605 name.c_str(),
5606 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005607 profileUpdated |= (status == NO_ERROR);
5608 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005609 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005610 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005611 AUDIO_DEVICE_IN_HDMI);
5612 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5613 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005614 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005615 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005616 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5617 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5618 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005619 name.c_str(),
5620 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005621 if (status != NO_ERROR) {
5622 continue;
5623 }
5624 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5625 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5626 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005627 name.c_str(),
5628 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005629 profileUpdated |= (status == NO_ERROR);
5630 }
5631
jiabin81772902018-04-02 17:52:27 -07005632 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005633 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005634 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005635 }
5636
5637 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5638}
5639
Eric Laurent5ada82e2019-08-29 17:53:54 -07005640void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005641{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005642 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005643 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005644 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005645 }
5646}
5647
jiabin6012f912018-11-02 17:06:30 -07005648bool AudioPolicyManager::isHapticPlaybackSupported()
5649{
5650 for (const auto& hwModule : mHwModules) {
5651 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5652 for (const auto &outProfile : outputProfiles) {
5653 struct audio_port audioPort;
5654 outProfile->toAudioPort(&audioPort);
5655 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5656 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5657 return true;
5658 }
5659 }
5660 }
5661 }
5662 return false;
5663}
5664
Carter Hsu325a8eb2022-01-19 19:56:51 +08005665bool AudioPolicyManager::isUltrasoundSupported()
5666{
5667 bool hasUltrasoundOutput = false;
5668 bool hasUltrasoundInput = false;
5669 for (const auto& hwModule : mHwModules) {
5670 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5671 if (!hasUltrasoundOutput) {
5672 for (const auto &outProfile : outputProfiles) {
5673 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5674 hasUltrasoundOutput = true;
5675 break;
5676 }
5677 }
5678 }
5679
5680 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5681 if (!hasUltrasoundInput) {
5682 for (const auto &inputProfile : inputProfiles) {
5683 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5684 hasUltrasoundInput = true;
5685 break;
5686 }
5687 }
5688 }
5689
5690 if (hasUltrasoundOutput && hasUltrasoundInput)
5691 return true;
5692 }
5693 return false;
5694}
5695
Atneya Nair698f5ef2022-12-15 16:15:09 -08005696bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5697{
5698 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5699 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5700 for (const auto& hwModule : mHwModules) {
5701 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5702 for (const auto &inputProfile : inputProfiles) {
5703 if ((inputProfile->getFlags() & mask) == mask) {
5704 return true;
5705 }
5706 }
5707 }
5708 return false;
5709}
5710
Eric Laurent8340e672019-11-06 11:01:08 -08005711bool AudioPolicyManager::isCallScreenModeSupported()
5712{
5713 return getConfig().isCallScreenModeSupported();
5714}
5715
5716
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005717status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005718{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005719 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005720 if (!sourceDesc->isConnected()) {
5721 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5722 return NO_ERROR;
5723 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005724 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5725 if (swOutput != 0) {
5726 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005727 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005728 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005729 }
jiabinbce0c1d2020-10-05 11:20:18 -07005730 if (releaseOutput(sourceDesc->portId())) {
5731 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5732 // no need to release audio patch here but just return NO_ERROR.
5733 return NO_ERROR;
5734 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005735 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005736 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005737 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005738 // close Hwoutput and remove from mHwOutputs
5739 } else {
5740 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5741 }
5742 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005743 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005744 sourceDesc->disconnect();
5745 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005746}
5747
François Gaffiec005e562018-11-06 15:04:49 +01005748sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5749 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005750{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005751 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005752 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005753 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005754 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005755 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5756 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005757 source = sourceDesc;
5758 break;
5759 }
5760 }
5761 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005762}
5763
Eric Laurentb4f42a92022-01-17 17:37:31 +01005764bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005765 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005766 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005767{
5768 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5769 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005770 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005771 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005772 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5773 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5774 return false;
5775 }
5776 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5777 return false;
5778 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005779 }
5780
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005781 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005782 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005783 if (profile == nullptr) {
5784 return false;
5785 }
5786
5787 // The caller can have the audio config criteria ignored by either passing a null ptr or
5788 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005789 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005790 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005791
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005792 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005793 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005794 return false;
5795 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005796 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005797 return true;
5798}
5799
5800void AudioPolicyManager::checkVirtualizerClientRoutes() {
5801 std::set<audio_stream_type_t> streamsToInvalidate;
5802 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005803 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5804 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005805 audio_attributes_t attr = client->attributes();
5806 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5807 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5808 audio_config_base_t clientConfig = client->config();
5809 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005810 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005811 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005812 streamsToInvalidate.insert(client->stream());
5813 }
5814 }
5815 }
5816
jiabinc44b3462022-12-08 12:52:31 -08005817 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005818}
5819
Eric Laurente191d1b2022-04-15 11:59:25 +02005820
5821bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5822 const sp<SwAudioOutputDescriptor>& outputDesc) {
5823 if (outputDesc->isDuplicated()) {
5824 return false;
5825 }
5826 DeviceVector devices = outputDesc->supportedDevices();
5827 for (size_t i = 0; i < mOutputs.size(); i++) {
5828 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5829 if (desc == outputDesc || desc->isDuplicated()) {
5830 continue;
5831 }
5832 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5833 if (!sharedDevices.isEmpty()
5834 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5835 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5836 return false;
5837 }
5838 }
5839 return true;
5840}
5841
5842
Eric Laurentfa0f6742021-08-17 18:39:44 +02005843status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005844 const audio_attributes_t *attr,
5845 audio_io_handle_t *output) {
5846 *output = AUDIO_IO_HANDLE_NONE;
5847
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005848 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5849 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5850 audio_config_t *configPtr = nullptr;
5851 audio_config_t config;
5852 if (mixerConfig != nullptr) {
5853 config = audio_config_initializer(mixerConfig);
5854 configPtr = &config;
5855 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005856 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005857 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005858 return BAD_VALUE;
5859 }
5860
5861 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005862 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005863 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005864 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005865 return BAD_VALUE;
5866 }
5867
Eric Laurente191d1b2022-04-15 11:59:25 +02005868 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005869 for (size_t i = 0; i < mOutputs.size(); i++) {
5870 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005871 if (!desc->isDuplicated()
5872 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5873 spatializerOutputs.push_back(desc);
5874 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005875 }
5876 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005877 mSpatializerOutput.clear();
5878 bool outputsChanged = false;
5879 for (const auto& desc : spatializerOutputs) {
5880 if (desc->mProfile == profile
5881 && (configPtr == nullptr
5882 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5883 mSpatializerOutput = desc;
5884 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5885 } else {
5886 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5887 " and devices %s", __func__, desc->mIoHandle,
5888 configPtr != nullptr ? configPtr->channel_mask : 0,
5889 devices.toString().c_str());
5890 closeOutput(desc->mIoHandle);
5891 outputsChanged = true;
5892 }
Eric Laurent39095982021-08-24 18:29:27 +02005893 }
5894
Eric Laurente191d1b2022-04-15 11:59:25 +02005895 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005896 sp<SwAudioOutputDescriptor> desc =
5897 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005898 if (desc != nullptr) {
5899 mSpatializerOutput = desc;
5900 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005901 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005902 }
5903
5904 checkVirtualizerClientRoutes();
5905
Eric Laurente191d1b2022-04-15 11:59:25 +02005906 if (outputsChanged) {
5907 mPreviousOutputs = mOutputs;
5908 mpClientInterface->onAudioPortListUpdate();
5909 }
5910
5911 if (mSpatializerOutput == nullptr) {
5912 ALOGV("%s could not open spatializer output with requested config", __func__);
5913 return BAD_VALUE;
5914 }
Eric Laurent39095982021-08-24 18:29:27 +02005915 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005916 ALOGV("%s returning new spatializer output %d", __func__, *output);
5917 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005918}
5919
Eric Laurentfa0f6742021-08-17 18:39:44 +02005920status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5921 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005922 return INVALID_OPERATION;
5923 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005924 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005925 return BAD_VALUE;
5926 }
Eric Laurent39095982021-08-24 18:29:27 +02005927
Eric Laurente191d1b2022-04-15 11:59:25 +02005928 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5929 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5930 closeOutput(mSpatializerOutput->mIoHandle);
5931 //from now on mSpatializerOutput is null
5932 checkVirtualizerClientRoutes();
5933 }
Eric Laurent39095982021-08-24 18:29:27 +02005934
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005935 return NO_ERROR;
5936}
5937
Eric Laurente552edb2014-03-10 17:42:56 -07005938// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005939// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005940// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005941uint32_t AudioPolicyManager::nextAudioPortGeneration()
5942{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005943 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005944}
5945
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005946static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005947 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5948 !audioPolicyXmlConfigFile.empty()) {
5949 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5950 if (ret == NO_ERROR) {
5951 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005952 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005953 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005954 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005955 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005956}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005957
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005958AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5959 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005960 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005961 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005962 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005963 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005964 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005965 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005966 mAudioPortGeneration(1),
5967 mBeaconMuteRefCount(0),
5968 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005969 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005970 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005971 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005972 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005973{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005974}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005975
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005976AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5977 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5978{
5979 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005980}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005981
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005982void AudioPolicyManager::loadConfig() {
5983 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005984 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005985 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005986 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005987}
5988
5989status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005990 {
5991 auto engLib = EngineLibrary::load(
5992 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5993 if (!engLib) {
5994 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5995 return NO_INIT;
5996 }
5997 mEngine = engLib->createEngine();
5998 if (mEngine == nullptr) {
5999 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
6000 return NO_INIT;
6001 }
François Gaffie2110e042015-03-24 08:41:51 +01006002 }
6003 mEngine->setObserver(this);
6004 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006005 if (status != NO_ERROR) {
6006 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6007 return status;
6008 }
François Gaffie2110e042015-03-24 08:41:51 +01006009
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006010 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006011 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6012 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6013
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006014 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006015 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006016 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006017
Eric Laurent3a4311c2014-03-17 12:00:47 -07006018 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01006019 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
6020 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
6021 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006022 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006023 }
jiabin9ff780e2018-03-19 18:19:52 -07006024 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07006025 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07006026 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07006027 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07006028 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07006029 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07006030 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07006031 }
6032 }
6033 }
Eric Laurente552edb2014-03-10 17:42:56 -07006034
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006035 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006036
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006037 // Silence ALOGV statements
6038 property_set("log.tag." LOG_TAG, "D");
6039
Eric Laurente552edb2014-03-10 17:42:56 -07006040 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006041 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006042}
6043
Eric Laurente0720872014-03-11 09:30:41 -07006044AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006045{
Eric Laurente552edb2014-03-10 17:42:56 -07006046 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006047 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006048 }
6049 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006050 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006051 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006052 mAvailableOutputDevices.clear();
6053 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006054 mOutputs.clear();
6055 mInputs.clear();
6056 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08006057 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006058 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006059}
6060
Eric Laurente0720872014-03-11 09:30:41 -07006061status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006062{
Eric Laurent87ffa392015-05-22 10:32:38 -07006063 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006064}
6065
Eric Laurente552edb2014-03-10 17:42:56 -07006066// ---
6067
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006068void AudioPolicyManager::onNewAudioModulesAvailable()
6069{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006070 DeviceVector newDevices;
6071 onNewAudioModulesAvailableInt(&newDevices);
6072 if (!newDevices.empty()) {
6073 nextAudioPortGeneration();
6074 mpClientInterface->onAudioPortListUpdate();
6075 }
6076}
6077
6078void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6079{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006080 for (const auto& hwModule : mHwModulesAll) {
6081 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6082 continue;
6083 }
6084 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
6085 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
6086 ALOGW("could not open HW module %s", hwModule->getName());
6087 continue;
6088 }
6089 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006090 // open all output streams needed to access attached devices.
6091 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006092 // This also validates mAvailableOutputDevices list
6093 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6094 if (!outProfile->canOpenNewIo()) {
6095 ALOGE("Invalid Output profile max open count %u for profile %s",
6096 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6097 continue;
6098 }
6099 if (!outProfile->hasSupportedDevices()) {
6100 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6101 continue;
6102 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006103 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6104 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006105 mTtsOutputAvailable = true;
6106 }
6107
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006108 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
6109 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
6110 sp<DeviceDescriptor> supportedDevice = 0;
6111 if (supportedDevices.contains(mDefaultOutputDevice)) {
6112 supportedDevice = mDefaultOutputDevice;
6113 } else {
6114 // choose first device present in profile's SupportedDevices also part of
6115 // mAvailableOutputDevices.
6116 if (availProfileDevices.isEmpty()) {
6117 continue;
6118 }
6119 supportedDevice = availProfileDevices.itemAt(0);
6120 }
6121 if (!mOutputDevicesAll.contains(supportedDevice)) {
6122 continue;
6123 }
6124 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6125 mpClientInterface);
6126 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006127 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6128 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006129 AUDIO_STREAM_DEFAULT,
6130 AUDIO_OUTPUT_FLAG_NONE, &output);
6131 if (status != NO_ERROR) {
6132 ALOGW("Cannot open output stream for devices %s on hw module %s",
6133 supportedDevice->toString().c_str(), hwModule->getName());
6134 continue;
6135 }
6136 for (const auto &device : availProfileDevices) {
6137 // give a valid ID to an attached device once confirmed it is reachable
6138 if (!device->isAttached()) {
6139 device->attach(hwModule);
6140 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006141 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006142 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006143 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6144 }
6145 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006146 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006147 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6148 mPrimaryOutput = outputDesc;
6149 }
Eric Laurent39095982021-08-24 18:29:27 +02006150 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006151 outputDesc->close();
6152 } else {
6153 addOutput(output, outputDesc);
6154 setOutputDevices(outputDesc,
6155 DeviceVector(supportedDevice),
6156 true,
6157 0,
6158 NULL);
6159 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006160 }
6161 // open input streams needed to access attached devices to validate
6162 // mAvailableInputDevices list
6163 for (const auto& inProfile : hwModule->getInputProfiles()) {
6164 if (!inProfile->canOpenNewIo()) {
6165 ALOGE("Invalid Input profile max open count %u for profile %s",
6166 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6167 continue;
6168 }
6169 if (!inProfile->hasSupportedDevices()) {
6170 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6171 continue;
6172 }
6173 // chose first device present in profile's SupportedDevices also part of
6174 // available input devices
6175 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
6176 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
6177 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006178 ALOGV("%s: Input device list is empty! for profile %s",
6179 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006180 continue;
6181 }
6182 sp<AudioInputDescriptor> inputDesc =
6183 new AudioInputDescriptor(inProfile, mpClientInterface);
6184
6185 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6186 status_t status = inputDesc->open(nullptr,
6187 availProfileDevices.itemAt(0),
6188 AUDIO_SOURCE_MIC,
6189 AUDIO_INPUT_FLAG_NONE,
6190 &input);
6191 if (status != NO_ERROR) {
6192 ALOGW("Cannot open input stream for device %s on hw module %s",
6193 availProfileDevices.toString().c_str(),
6194 hwModule->getName());
6195 continue;
6196 }
6197 for (const auto &device : availProfileDevices) {
6198 // give a valid ID to an attached device once confirmed it is reachable
6199 if (!device->isAttached()) {
6200 device->attach(hwModule);
6201 device->importAudioPortAndPickAudioProfile(inProfile, true);
6202 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006203 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006204 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6205 }
6206 }
6207 inputDesc->close();
6208 }
6209 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006210
6211 // Check if spatializer outputs can be closed until used.
6212 // mOutputs vector never contains duplicated outputs at this point.
6213 std::vector<audio_io_handle_t> outputsClosed;
6214 for (size_t i = 0; i < mOutputs.size(); i++) {
6215 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6216 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6217 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6218 outputsClosed.push_back(desc->mIoHandle);
6219 desc->close();
6220 }
6221 }
6222 for (auto output : outputsClosed) {
6223 removeOutput(output);
6224 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006225}
6226
Eric Laurent98e38192018-02-15 18:31:53 -08006227void AudioPolicyManager::addOutput(audio_io_handle_t output,
6228 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006229{
Eric Laurent1c333e22014-05-20 10:48:17 -07006230 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006231 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006232 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006233 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006234 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006235}
6236
François Gaffie53615e22015-03-19 09:24:12 +01006237void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6238{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006239 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6240 ALOGV("%s: removing primary output", __func__);
6241 mPrimaryOutput = nullptr;
6242 }
François Gaffie53615e22015-03-19 09:24:12 +01006243 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006244 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006245}
6246
Eric Laurent98e38192018-02-15 18:31:53 -08006247void AudioPolicyManager::addInput(audio_io_handle_t input,
6248 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006249{
Eric Laurent1c333e22014-05-20 10:48:17 -07006250 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006251 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006252}
Eric Laurente552edb2014-03-10 17:42:56 -07006253
François Gaffie11d30102018-11-02 16:09:09 +01006254status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006255 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006256 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006257{
François Gaffie11d30102018-11-02 16:09:09 +01006258 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006259 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006260 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006261
François Gaffie11d30102018-11-02 16:09:09 +01006262 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006263 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006264 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006265 }
Eric Laurente552edb2014-03-10 17:42:56 -07006266
Eric Laurent3b73df72014-03-11 09:06:29 -07006267 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006268 // first call getAudioPort to get the supported attributes from the HAL
6269 struct audio_port_v7 port = {};
6270 device->toAudioPort(&port);
6271 status_t status = mpClientInterface->getAudioPort(&port);
6272 if (status == NO_ERROR) {
6273 device->importAudioPort(port);
6274 }
6275
6276 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006277 for (size_t i = 0; i < mOutputs.size(); i++) {
6278 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006279 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006280 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006281 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6282 mOutputs.keyAt(i), device->toString().c_str());
6283 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006284 }
6285 }
6286 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006287 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006288 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006289 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6290 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006291 if (profile->supportsDevice(device)) {
6292 profiles.add(profile);
6293 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6294 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006295 }
6296 }
6297 }
6298
Eric Laurent7b279bb2015-12-14 10:18:23 -08006299 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006300
Eric Laurente552edb2014-03-10 17:42:56 -07006301 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006302 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006303 return BAD_VALUE;
6304 }
6305
6306 // open outputs for matching profiles if needed. Direct outputs are also opened to
6307 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6308 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006309 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006310
6311 // nothing to do if one output is already opened for this profile
6312 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006313 for (j = 0; j < outputs.size(); j++) {
6314 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006315 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006316 // matching profile: save the sample rates, format and channel masks supported
6317 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006318 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006319 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006320 }
Eric Laurente552edb2014-03-10 17:42:56 -07006321 break;
6322 }
6323 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006324 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006325 continue;
6326 }
6327
Eric Laurent3974e3b2017-12-07 17:58:43 -08006328 if (!profile->canOpenNewIo()) {
6329 ALOGW("Max Output number %u already opened for this profile %s",
6330 profile->maxOpenCount, profile->getTagName().c_str());
6331 continue;
6332 }
6333
Eric Laurent83efe1c2017-07-09 16:51:08 -07006334 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07006335 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006336 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6337 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006338 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006339 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006340 profiles.removeAt(profile_index);
6341 profile_index--;
6342 } else {
6343 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006344 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006345 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006346 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6347 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006348 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006349 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006350
François Gaffie11d30102018-11-02 16:09:09 +01006351 if (device_distinguishes_on_address(deviceType)) {
6352 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6353 device->toString().c_str());
6354 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
6355 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006356 }
Eric Laurente552edb2014-03-10 17:42:56 -07006357 ALOGV("checkOutputsForDevice(): adding output %d", output);
6358 }
6359 }
6360
6361 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006362 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006363 return BAD_VALUE;
6364 }
Eric Laurentd4692962014-05-05 18:13:44 -07006365 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006366 // check if one opened output is not needed any more after disconnecting one device
6367 for (size_t i = 0; i < mOutputs.size(); i++) {
6368 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006369 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006370 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006371 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006372 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006373 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006374 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006375 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6376 mOutputs.keyAt(i));
6377 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006378 }
Eric Laurente552edb2014-03-10 17:42:56 -07006379 }
6380 }
Eric Laurentd4692962014-05-05 18:13:44 -07006381 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006382 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006383 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6384 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006385 if (!profile->supportsDevice(device)) {
6386 continue;
6387 }
6388 ALOGV("checkOutputsForDevice(): "
6389 "clearing direct output profile %zu on module %s",
6390 j, hwModule->getName());
6391 profile->clearAudioProfiles();
6392 if (!profile->hasDynamicAudioProfile()) {
6393 continue;
6394 }
6395 // When a device is disconnected, if there is an IOProfile that contains dynamic
6396 // profiles and supports the disconnected device, call getAudioPort to repopulate
6397 // the capabilities of the devices that is supported by the IOProfile.
6398 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6399 if (supportedDevice == device ||
6400 !mAvailableOutputDevices.contains(supportedDevice)) {
6401 continue;
6402 }
6403 struct audio_port_v7 port;
6404 supportedDevice->toAudioPort(&port);
6405 status_t status = mpClientInterface->getAudioPort(&port);
6406 if (status == NO_ERROR) {
6407 supportedDevice->importAudioPort(port);
6408 }
Eric Laurente552edb2014-03-10 17:42:56 -07006409 }
6410 }
6411 }
6412 }
6413 return NO_ERROR;
6414}
6415
François Gaffie11d30102018-11-02 16:09:09 +01006416status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006417 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006418{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006419 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006420
François Gaffie11d30102018-11-02 16:09:09 +01006421 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006422 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006423 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006424 }
6425
Eric Laurentd4692962014-05-05 18:13:44 -07006426 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006427 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006428 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006429 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006430 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006431 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006432 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006433 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006434
François Gaffie11d30102018-11-02 16:09:09 +01006435 if (profile->supportsDevice(device)) {
6436 profiles.add(profile);
6437 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6438 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006439 }
6440 }
6441 }
6442
Eric Laurent0dd51852019-04-19 18:18:58 -07006443 if (profiles.isEmpty()) {
6444 ALOGW("%s: No input profile available for device %s",
6445 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006446 return BAD_VALUE;
6447 }
6448
6449 // open inputs for matching profiles if needed. Direct inputs are also opened to
6450 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6451 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6452
Eric Laurent1c333e22014-05-20 10:48:17 -07006453 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006454
Eric Laurentd4692962014-05-05 18:13:44 -07006455 // nothing to do if one input is already opened for this profile
6456 size_t input_index;
6457 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6458 desc = mInputs.valueAt(input_index);
6459 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006460 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006461 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006462 }
Eric Laurentd4692962014-05-05 18:13:44 -07006463 break;
6464 }
6465 }
6466 if (input_index != mInputs.size()) {
6467 continue;
6468 }
6469
Eric Laurent3974e3b2017-12-07 17:58:43 -08006470 if (!profile->canOpenNewIo()) {
6471 ALOGW("Max Input number %u already opened for this profile %s",
6472 profile->maxOpenCount, profile->getTagName().c_str());
6473 continue;
6474 }
6475
Eric Laurentfe231122017-11-17 17:48:06 -08006476 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006477 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006478 status_t status = desc->open(nullptr,
6479 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006480 AUDIO_SOURCE_MIC,
6481 AUDIO_INPUT_FLAG_NONE,
6482 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006483
Eric Laurentcf2c0212014-07-25 16:20:43 -07006484 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006485 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006486 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006487 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006488 mpClientInterface->setParameters(input, String8(param));
6489 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006490 }
François Gaffie11d30102018-11-02 16:09:09 +01006491 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006492 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006493 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006494 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006495 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006496 }
6497
Eric Laurent0dd51852019-04-19 18:18:58 -07006498 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006499 addInput(input, desc);
6500 }
6501 } // endif input != 0
6502
Eric Laurentcf2c0212014-07-25 16:20:43 -07006503 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006504 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006505 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006506 profiles.removeAt(profile_index);
6507 profile_index--;
6508 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006509 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006510 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006511 }
Eric Laurentd4692962014-05-05 18:13:44 -07006512 ALOGV("checkInputsForDevice(): adding input %d", input);
6513 }
6514 } // end scan profiles
6515
6516 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006517 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006518 return BAD_VALUE;
6519 }
6520 } else {
6521 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006522 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006523 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006524 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006525 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006526 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006527 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006528 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006529 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6530 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006531 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006532 }
6533 }
6534 }
6535 } // end disconnect
6536
6537 return NO_ERROR;
6538}
6539
6540
Eric Laurente0720872014-03-11 09:30:41 -07006541void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006542{
6543 ALOGV("closeOutput(%d)", output);
6544
François Gaffie1c878552018-11-22 16:53:21 +01006545 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6546 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006547 ALOGW("closeOutput() unknown output %d", output);
6548 return;
6549 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006550 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006551 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006552
Eric Laurente552edb2014-03-10 17:42:56 -07006553 // look for duplicated outputs connected to the output being removed.
6554 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006555 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6556 if (dupOutput->isDuplicated() &&
6557 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6558 sp<SwAudioOutputDescriptor> remainingOutput =
6559 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006560 // As all active tracks on duplicated output will be deleted,
6561 // and as they were also referenced on the other output, the reference
6562 // count for their stream type must be adjusted accordingly on
6563 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006564 const bool wasActive = remainingOutput->isActive();
6565 // Note: no-op on the closing output where all clients has already been set inactive
6566 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006567 // stop() will be a no op if the output is still active but is needed in case all
6568 // active streams refcounts where cleared above
6569 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006570 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006571 }
Eric Laurente552edb2014-03-10 17:42:56 -07006572 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6573 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6574
6575 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006576 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006577 }
6578 }
6579
Eric Laurent05b90f82014-08-27 15:32:29 -07006580 nextAudioPortGeneration();
6581
François Gaffie1c878552018-11-22 16:53:21 +01006582 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006583 if (index >= 0) {
6584 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006585 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6586 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006587 mAudioPatches.removeItemsAt(index);
6588 mpClientInterface->onAudioPatchListUpdate();
6589 }
6590
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006591 if (closingOutputWasActive) {
6592 closingOutput->stop();
6593 }
François Gaffie1c878552018-11-22 16:53:21 +01006594 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006595
François Gaffie53615e22015-03-19 09:24:12 +01006596 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006597 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006598 if (closingOutput == mSpatializerOutput) {
6599 mSpatializerOutput.clear();
6600 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006601
6602 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6603 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006604 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006605 bool directOutputOpen = false;
6606 for (size_t i = 0; i < mOutputs.size(); i++) {
6607 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6608 directOutputOpen = true;
6609 break;
6610 }
6611 }
6612 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006613 ALOGV("no direct outputs open, reset MSD patches");
6614 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6615 // how output devices for patching are resolved. Avoid by caching and reusing the
6616 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6617 // devices to patch to. This may be complicated by the fact that devices may become
6618 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006619 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006620 }
6621 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006622}
6623
6624void AudioPolicyManager::closeInput(audio_io_handle_t input)
6625{
6626 ALOGV("closeInput(%d)", input);
6627
6628 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6629 if (inputDesc == NULL) {
6630 ALOGW("closeInput() unknown input %d", input);
6631 return;
6632 }
6633
Eric Laurent6a94d692014-05-20 11:18:06 -07006634 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006635
François Gaffie11d30102018-11-02 16:09:09 +01006636 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006637 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006638 if (index >= 0) {
6639 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006640 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6641 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006642 mAudioPatches.removeItemsAt(index);
6643 mpClientInterface->onAudioPatchListUpdate();
6644 }
6645
Eric Laurentfe231122017-11-17 17:48:06 -08006646 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006647 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006648
François Gaffie11d30102018-11-02 16:09:09 +01006649 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6650 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006651 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006652 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006653 }
Eric Laurente552edb2014-03-10 17:42:56 -07006654}
6655
François Gaffie11d30102018-11-02 16:09:09 +01006656SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6657 const DeviceVector &devices,
6658 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006659{
6660 SortedVector<audio_io_handle_t> outputs;
6661
François Gaffie11d30102018-11-02 16:09:09 +01006662 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006663 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006664 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006665 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006666 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006667 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006668 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006669 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006670 outputs.add(openOutputs.keyAt(i));
6671 }
6672 }
6673 return outputs;
6674}
6675
Mikhail Naganov37977152018-07-11 15:54:44 -07006676void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6677{
6678 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6679 // output is suspended before any tracks are moved to it
6680 checkA2dpSuspend();
6681 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006682 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006683 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006684 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006685 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006686 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6687 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6688 // configuration changes will ultimately be rerouted correctly. We can still avoid
6689 // unnecessary rerouting by caching and reusing the arguments to
6690 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6691 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006692 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006693 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006694 // an event that changed routing likely occurred, inform upper layers
6695 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006696}
6697
François Gaffiec005e562018-11-06 15:04:49 +01006698bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6699 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006700{
François Gaffiec005e562018-11-06 15:04:49 +01006701 return mEngine->getProductStrategyForAttributes(lAttr) ==
6702 mEngine->getProductStrategyForAttributes(rAttr);
6703}
6704
Francois Gaffieff1eb522020-05-06 18:37:04 +02006705void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6706{
6707 for (size_t i = 0; i < mAudioSources.size(); i++) {
6708 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6709 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006710 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006711 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006712 connectAudioSource(sourceDesc);
6713 }
6714 }
6715}
6716
6717void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6718{
6719 for (size_t i = 0; i < mAudioSources.size(); i++) {
6720 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6721 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6722 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6723 disconnectAudioSource(sourceDesc);
6724 }
6725 }
6726}
6727
François Gaffiec005e562018-11-06 15:04:49 +01006728void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6729{
6730 auto psId = mEngine->getProductStrategyForAttributes(attr);
6731
6732 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6733 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006734
François Gaffie11d30102018-11-02 16:09:09 +01006735 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6736 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006737
Eric Laurentc209fe42020-06-05 18:11:23 -07006738 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006739 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006740 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006741 // take into account dynamic audio policies related changes: if a client is now associated
6742 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006743 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006744 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6745 if (desc->isDuplicated()) {
6746 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006747 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006748 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6749 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6750 continue;
6751 }
6752 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006753 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006754 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6755 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6756 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006757 if (status != OK) {
6758 continue;
6759 }
yucliuf4de36d2020-09-14 14:57:56 -07006760 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006761 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006762 maxLatency = desc->latency();
6763 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006764 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006765 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006766 }
6767 }
6768
Eric Laurent56ed8842022-11-15 16:04:41 +01006769 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006770 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6771 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006772 for (audio_io_handle_t srcOut : srcOutputs) {
6773 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006774 if (desc == nullptr) continue;
6775
6776 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006777 maxLatency = desc->latency();
6778 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006779
Eric Laurent56ed8842022-11-15 16:04:41 +01006780 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006781 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006782 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006783 // a client on a non direct outputs has necessarily a linear PCM format
6784 // so we can call selectOutput() safely
6785 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6786 client->flags(),
6787 client->config().format,
6788 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006789 client->config().sample_rate,
6790 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006791 if (newOutput != srcOut) {
6792 invalidate = true;
6793 break;
6794 }
6795 } else {
6796 sp<IOProfile> profile = getProfileForOutput(newDevices,
6797 client->config().sample_rate,
6798 client->config().format,
6799 client->config().channel_mask,
6800 client->flags(),
6801 true /* directOnly */);
6802 if (profile != desc->mProfile) {
6803 invalidate = true;
6804 break;
6805 }
6806 }
6807 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006808 // mute strategy while moving tracks from one output to another
6809 if (invalidate) {
6810 invalidatedOutputs.push_back(desc);
6811 if (desc->isStrategyActive(psId)) {
6812 setStrategyMute(psId, true, desc);
6813 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6814 newDevices.types());
6815 }
Eric Laurente552edb2014-03-10 17:42:56 -07006816 }
François Gaffiec005e562018-11-06 15:04:49 +01006817 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006818 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006819 connectAudioSource(source);
6820 }
Eric Laurente552edb2014-03-10 17:42:56 -07006821 }
6822
Eric Laurent56ed8842022-11-15 16:04:41 +01006823 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6824 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6825 std::to_string(srcOutputs[0]).c_str(),
6826 std::to_string(dstOutputs[0]).c_str());
6827
François Gaffiec005e562018-11-06 15:04:49 +01006828 // Move effects associated to this stream from previous output to new output
6829 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006830 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006831 }
François Gaffiec005e562018-11-06 15:04:49 +01006832 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006833 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006834 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006835 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006836 desc->setTracksInvalidatedStatusByStrategy(psId);
6837 }
Eric Laurente552edb2014-03-10 17:42:56 -07006838 }
6839 }
6840}
6841
Eric Laurente0720872014-03-11 09:30:41 -07006842void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006843{
François Gaffiec005e562018-11-06 15:04:49 +01006844 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6845 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6846 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006847 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006848 }
Eric Laurente552edb2014-03-10 17:42:56 -07006849}
6850
Kevin Rocard153f92d2018-12-18 18:33:28 -08006851void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08006852 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006853 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006854 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006855 for (size_t i = 0; i < mOutputs.size(); i++) {
6856 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6857 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006858 sp<AudioPolicyMix> primaryMix;
6859 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006860 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006861 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6862 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
6863 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006864 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6865 for (auto &secondaryMix : secondaryMixes) {
6866 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6867 if (outputDesc != nullptr &&
6868 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6869 secondaryDescs.push_back(outputDesc);
6870 }
6871 }
6872
jiabinc44b3462022-12-08 12:52:31 -08006873 if (status != OK &&
6874 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
6875 // When it failed to query secondary output, only invalidate the client that is not
6876 // MMAP. The reason is that MMAP stream will not support secondary output.
6877 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00006878 } else if (!std::equal(
6879 client->getSecondaryOutputs().begin(),
6880 client->getSecondaryOutputs().end(),
6881 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006882 if (!audio_is_linear_pcm(client->config().format)) {
6883 // If the format is not PCM, the tracks should be invalidated to get correct
6884 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08006885 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00006886 } else {
6887 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6888 std::vector<audio_io_handle_t> secondaryOutputIds;
6889 for (const auto &secondaryDesc: secondaryDescs) {
6890 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6891 weakSecondaryDescs.push_back(secondaryDesc);
6892 }
6893 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6894 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006895 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006896 }
6897 }
6898 }
jiabin10a03f12021-05-07 23:46:28 +00006899 if (!trackSecondaryOutputs.empty()) {
6900 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6901 }
jiabinc44b3462022-12-08 12:52:31 -08006902 if (!clientsToInvalidate.empty()) {
6903 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
6904 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006905 }
6906}
6907
Eric Laurent2517af32020-11-25 15:31:27 +01006908bool AudioPolicyManager::isScoRequestedForComm() const {
6909 AudioDeviceTypeAddrVector devices;
6910 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6911 for (const auto &device : devices) {
6912 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6913 return true;
6914 }
6915 }
6916 return false;
6917}
6918
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006919bool AudioPolicyManager::isHearingAidUsedForComm() const {
6920 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6921 true /*fromCache*/);
6922 for (const auto &device : devices) {
6923 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6924 return true;
6925 }
6926 }
6927 return false;
6928}
6929
6930
Eric Laurente0720872014-03-11 09:30:41 -07006931void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006932{
François Gaffie53615e22015-03-19 09:24:12 +01006933 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006934 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006935 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006936 return;
6937 }
6938
Eric Laurent3a4311c2014-03-17 12:00:47 -07006939 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006940 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6941 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006942 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006943
6944 // if suspended, restore A2DP output if:
6945 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006946 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006947 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006948 //
Eric Laurentf732e072016-08-03 19:30:28 -07006949 // if not suspended, suspend A2DP output if:
6950 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006951 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006952 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006953 //
6954 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006955 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006956 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006957 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006958 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006959
6960 mpClientInterface->restoreOutput(a2dpOutput);
6961 mA2dpSuspended = false;
6962 }
6963 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006964 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006965 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006966 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006967 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006968
6969 mpClientInterface->suspendOutput(a2dpOutput);
6970 mA2dpSuspended = true;
6971 }
6972 }
6973}
6974
François Gaffie11d30102018-11-02 16:09:09 +01006975DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6976 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006977{
François Gaffie11d30102018-11-02 16:09:09 +01006978 DeviceVector devices;
6979
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006980 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006981 if (index >= 0) {
6982 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006983 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006984 ALOGV("%s device %s forced by patch %d", __func__,
6985 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6986 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006987 }
6988 }
6989
Dean Wheatley514b4312020-06-17 21:45:00 +10006990 // Do not retrieve engine device for outputs through MSD
6991 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6992 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6993 return outputDesc->devices();
6994 }
6995
Eric Laurent97ac8712018-07-27 18:59:02 -07006996 // Honor explicit routing requests only if no client using default routing is active on this
6997 // input: a specific app can not force routing for other apps by setting a preferred device.
6998 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006999 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007000 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007001 if (device != nullptr) {
7002 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007003 }
7004
François Gaffiea807ef92018-11-05 10:44:33 +01007005 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7006 // of setForceUse / Default Bus device here
7007 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7008 if (device != nullptr) {
7009 return DeviceVector(device);
7010 }
7011
François Gaffiec005e562018-11-06 15:04:49 +01007012 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7013 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7014 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307015 auto hasStreamActive = [&](auto stream) {
7016 return hasStream(streams, stream) && isStreamActive(stream, 0);
7017 };
Eric Laurent484e9272018-06-07 17:29:23 -07007018
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307019 auto doGetOutputDevicesForVoice = [&]() {
7020 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007021 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307022 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007023 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7024 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307025 };
7026
7027 // With low-latency playing on speaker, music on WFD, when the first low-latency
7028 // output is stopped, getNewOutputDevices checks for a product strategy
7029 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007030 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307031 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7032 // stream is associated to the output descriptor.
7033 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7034 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7035 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7036 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007037 // Retrieval of devices for voice DL is done on primary output profile, cannot
7038 // check the route (would force modifying configuration file for this profile)
7039 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7040 break;
7041 }
Eric Laurente552edb2014-03-10 17:42:56 -07007042 }
François Gaffiec005e562018-11-06 15:04:49 +01007043 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007044 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007045}
7046
François Gaffie11d30102018-11-02 16:09:09 +01007047sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7048 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007049{
François Gaffie11d30102018-11-02 16:09:09 +01007050 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007051
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007052 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007053 if (index >= 0) {
7054 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007055 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007056 ALOGV("getNewInputDevice() device %s forced by patch %d",
7057 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7058 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007059 }
7060 }
7061
Eric Laurent97ac8712018-07-27 18:59:02 -07007062 // Honor explicit routing requests only if no client using default routing is active on this
7063 // input: a specific app can not force routing for other apps by setting a preferred device.
7064 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007065 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7066 if (device != nullptr) {
7067 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007068 }
7069
Eric Laurentdc95a252018-04-12 12:46:56 -07007070 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007071 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007072 audio_attributes_t attributes;
7073 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007074 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007075 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7076 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007077 attributes = topClient->attributes();
7078 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007079 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007080 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007081 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7082 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007083 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007084 }
7085
Francois Gaffie716e1432019-01-14 16:58:59 +01007086 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7087 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007088 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007089 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007090 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007091 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007092
Eric Laurente552edb2014-03-10 17:42:56 -07007093 return device;
7094}
7095
Eric Laurent794fde22016-03-11 09:50:45 -08007096bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7097 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007098 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007099}
7100
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007101status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007102 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007103 if (devices == nullptr) {
7104 return BAD_VALUE;
7105 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007106
Andy Hung6d23c0f2022-02-16 09:37:15 -08007107 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007108 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7109 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007110 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007111 for (const auto& device : curDevices) {
7112 devices->push_back(device->getDeviceTypeAddr());
7113 }
7114 return NO_ERROR;
7115}
7116
Eric Laurente0720872014-03-11 09:30:41 -07007117void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007118 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007119 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007120 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007121 updateDevicesAndOutputs();
7122 break;
7123 default:
7124 break;
7125 }
7126}
7127
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007128uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007129
7130 // skip beacon mute management if a dedicated TTS output is available
7131 if (mTtsOutputAvailable) {
7132 return 0;
7133 }
7134
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007135 switch(event) {
7136 case STARTING_OUTPUT:
7137 mBeaconMuteRefCount++;
7138 break;
7139 case STOPPING_OUTPUT:
7140 if (mBeaconMuteRefCount > 0) {
7141 mBeaconMuteRefCount--;
7142 }
7143 break;
7144 case STARTING_BEACON:
7145 mBeaconPlayingRefCount++;
7146 break;
7147 case STOPPING_BEACON:
7148 if (mBeaconPlayingRefCount > 0) {
7149 mBeaconPlayingRefCount--;
7150 }
7151 break;
7152 }
7153
7154 if (mBeaconMuteRefCount > 0) {
7155 // any playback causes beacon to be muted
7156 return setBeaconMute(true);
7157 } else {
7158 // no other playback: unmute when beacon starts playing, mute when it stops
7159 return setBeaconMute(mBeaconPlayingRefCount == 0);
7160 }
7161}
7162
7163uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7164 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7165 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7166 // keep track of muted state to avoid repeating mute/unmute operations
7167 if (mBeaconMuted != mute) {
7168 // mute/unmute AUDIO_STREAM_TTS on all outputs
7169 ALOGV("\t muting %d", mute);
7170 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007171 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7172 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7173 ALOGV("\t no tts volume source available");
7174 return 0;
7175 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007176 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007177 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007178 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007179 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007180 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007181 maxLatency = latency;
7182 }
7183 }
7184 mBeaconMuted = mute;
7185 return maxLatency;
7186 }
7187 return 0;
7188}
7189
Eric Laurente0720872014-03-11 09:30:41 -07007190void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007191{
François Gaffiec005e562018-11-06 15:04:49 +01007192 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007193 mPreviousOutputs = mOutputs;
7194}
7195
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007196uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007197 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007198 uint32_t delayMs)
7199{
7200 // mute/unmute strategies using an incompatible device combination
7201 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7202 // if unmuting, unmute only after the specified delay
7203 if (outputDesc->isDuplicated()) {
7204 return 0;
7205 }
7206
7207 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007208 DeviceVector devices = outputDesc->devices();
7209 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007210
François Gaffiec005e562018-11-06 15:04:49 +01007211 auto productStrategies = mEngine->getOrderedProductStrategies();
7212 for (const auto &productStrategy : productStrategies) {
7213 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7214 DeviceVector curDevices =
7215 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7216 curDevices = curDevices.filter(outputDesc->supportedDevices());
7217 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007218 bool doMute = false;
7219
François Gaffiec005e562018-11-06 15:04:49 +01007220 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007221 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007222 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7223 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007224 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007225 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007226 }
Eric Laurent99401132014-05-07 19:48:15 -07007227 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007228 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007229 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007230 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007231 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007232 continue;
7233 }
François Gaffiec005e562018-11-06 15:04:49 +01007234 ALOGVV("%s() %s (curDevice %s)", __func__,
7235 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7236 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7237 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007238 if (mute) {
7239 // FIXME: should not need to double latency if volume could be applied
7240 // immediately by the audioflinger mixer. We must account for the delay
7241 // between now and the next time the audioflinger thread for this output
7242 // will process a buffer (which corresponds to one buffer size,
7243 // usually 1/2 or 1/4 of the latency).
7244 if (muteWaitMs < desc->latency() * 2) {
7245 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007246 }
7247 }
7248 }
7249 }
7250 }
7251 }
7252
Eric Laurent99401132014-05-07 19:48:15 -07007253 // temporary mute output if device selection changes to avoid volume bursts due to
7254 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007255 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007256 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007257
Eric Laurentdc462862016-07-19 12:29:53 -07007258 if (muteWaitMs < tempMuteWaitMs) {
7259 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007260 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007261
7262 // If recommended duration is defined, replace temporary mute duration to avoid
7263 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7264 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7265 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7266 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7267 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7268
François Gaffieaaac0fd2018-11-22 17:56:39 +01007269 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7270 // make sure that we do not start the temporary mute period too early in case of
7271 // delayed device change
7272 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7273 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007274 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007275 }
7276 }
7277
Eric Laurente552edb2014-03-10 17:42:56 -07007278 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7279 if (muteWaitMs > delayMs) {
7280 muteWaitMs -= delayMs;
7281 usleep(muteWaitMs * 1000);
7282 return muteWaitMs;
7283 }
7284 return 0;
7285}
7286
François Gaffie11d30102018-11-02 16:09:09 +01007287uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7288 const DeviceVector &devices,
7289 bool force,
7290 int delayMs,
7291 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02007292 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07007293{
jiabin3ff8d7d2022-12-13 06:27:44 +00007294 // TODO(b/262404095): Consider if the output need to be reopened.
François Gaffie11d30102018-11-02 16:09:09 +01007295 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007296 uint32_t muteWaitMs;
7297
7298 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01007299 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
7300 nullptr /* patchHandle */, requiresMuteCheck);
7301 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
7302 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07007303 return muteWaitMs;
7304 }
Eric Laurente552edb2014-03-10 17:42:56 -07007305
7306 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007307 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007308 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007309 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007310
François Gaffie11d30102018-11-02 16:09:09 +01007311 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7312
7313 if (!filteredDevices.isEmpty()) {
7314 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007315 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007316
7317 // if the outputs are not materially active, there is no need to mute.
7318 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007319 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007320 } else {
7321 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7322 muteWaitMs = 0;
7323 }
Eric Laurente552edb2014-03-10 17:42:56 -07007324
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007325 bool outputRouted = outputDesc->isRouted();
7326
Eric Laurent79ea9582020-06-11 18:49:24 -07007327 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7328 // output profile or if new device is not supported AND previous device(s) is(are) still
7329 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007330 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007331 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7332 // restore previous device after evaluating strategy mute state
7333 outputDesc->setDevices(prevDevices);
7334 return muteWaitMs;
7335 }
7336
Eric Laurente552edb2014-03-10 17:42:56 -07007337 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007338 // the requested device is AUDIO_DEVICE_NONE
7339 // OR the requested device is the same as current device
7340 // AND force is not specified
7341 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007342 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007343 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007344 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7345 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007346 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7347 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7348 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7349 }
Eric Laurente552edb2014-03-10 17:42:56 -07007350 return muteWaitMs;
7351 }
7352
François Gaffie11d30102018-11-02 16:09:09 +01007353 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007354
Eric Laurente552edb2014-03-10 17:42:56 -07007355 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007356 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007357 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007358 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007359 PatchBuilder patchBuilder;
7360 patchBuilder.addSource(outputDesc);
7361 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7362 for (const auto &filteredDevice : filteredDevices) {
7363 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007364 }
7365
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007366 // Add half reported latency to delayMs when muteWaitMs is null in order
7367 // to avoid disordered sequence of muting volume and changing devices.
7368 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7369 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007370 }
Eric Laurente552edb2014-03-10 17:42:56 -07007371
7372 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007373 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007374
7375 return muteWaitMs;
7376}
7377
Eric Laurentc75307b2015-03-17 15:29:32 -07007378status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007379 int delayMs,
7380 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007381{
Eric Laurent6a94d692014-05-20 11:18:06 -07007382 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007383 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7384 return INVALID_OPERATION;
7385 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007386 if (patchHandle) {
7387 index = mAudioPatches.indexOfKey(*patchHandle);
7388 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007389 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007390 }
7391 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007392 return INVALID_OPERATION;
7393 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007394 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007395 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007396 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007397 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007398 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007399 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007400 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007401 return status;
7402}
7403
7404status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007405 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007406 bool force,
7407 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007408{
7409 status_t status = NO_ERROR;
7410
Eric Laurent1f2f2232014-06-02 12:01:23 -07007411 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007412 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7413 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007414
François Gaffie11d30102018-11-02 16:09:09 +01007415 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007416 PatchBuilder patchBuilder;
7417 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007418 // AUDIO_SOURCE_HOTWORD is for internal use only:
7419 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007420 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7421 auto result = usecase;
7422 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7423 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7424 }
7425 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007426 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007427 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007428 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007429 }
7430 }
7431 return status;
7432}
7433
Eric Laurent6a94d692014-05-20 11:18:06 -07007434status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7435 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007436{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007437 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007438 ssize_t index;
7439 if (patchHandle) {
7440 index = mAudioPatches.indexOfKey(*patchHandle);
7441 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007442 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007443 }
7444 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007445 return INVALID_OPERATION;
7446 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007447 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007448 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007449 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007450 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007451 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007452 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007453 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007454 return status;
7455}
7456
François Gaffie11d30102018-11-02 16:09:09 +01007457sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007458 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007459 audio_format_t& format,
7460 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007461 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007462{
7463 // Choose an input profile based on the requested capture parameters: select the first available
7464 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007465 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007466 //
7467 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7468 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007469
Atneya Nair0f0a8032022-12-12 16:20:12 -08007470 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7471 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7472 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7473
7474 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007475
jiabin2fd710d2022-05-02 23:20:22 +00007476 for (;;) {
7477 sp<IOProfile> firstInexact = nullptr;
7478 uint32_t updatedSamplingRate = 0;
7479 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7480 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7481 for (const auto& hwModule : mHwModules) {
7482 for (const auto& profile : hwModule->getInputProfiles()) {
7483 // profile->log();
7484 //updatedFormat = format;
7485 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7486 &samplingRate /*updatedSamplingRate*/,
7487 format,
7488 &format, /*updatedFormat*/
7489 channelMask,
7490 &channelMask /*updatedChannelMask*/,
7491 // FIXME ugly cast
7492 (audio_output_flags_t) flags,
7493 true /*exactMatchRequiredForInputFlags*/)) {
7494 return profile;
7495 }
7496 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7497 samplingRate,
7498 &updatedSamplingRate,
7499 format,
7500 &updatedFormat,
7501 channelMask,
7502 &updatedChannelMask,
7503 // FIXME ugly cast
7504 (audio_output_flags_t) flags,
7505 false /*exactMatchRequiredForInputFlags*/)) {
7506 firstInexact = profile;
7507 }
7508 }
7509 }
7510
7511 if (firstInexact != nullptr) {
7512 samplingRate = updatedSamplingRate;
7513 format = updatedFormat;
7514 channelMask = updatedChannelMask;
7515 return firstInexact;
7516 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7517 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7518 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7519 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7520 flags = AUDIO_INPUT_FLAG_NONE;
7521 } else { // fail
7522 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7523 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7524 samplingRate, format, channelMask, oriFlags);
7525 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007526 }
7527 }
jiabin2fd710d2022-05-02 23:20:22 +00007528
7529 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007530}
7531
François Gaffieaaac0fd2018-11-22 17:56:39 +01007532float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7533 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007534 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007535 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007536{
jiabin9a3361e2019-10-01 09:38:30 -07007537 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007538
7539 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7540 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7541 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7542 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007543 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7544 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7545 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7546 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7547 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007548
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007549 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007550 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7551 mOutputs.isActive(ringVolumeSrc, 0)) {
7552 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007553 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007554 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007555 }
7556
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007557 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007558 if ((volumeSource != callVolumeSrc && (isInCall() ||
7559 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007560 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007561 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7562 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007563 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7564 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7565 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007566 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007567 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007568 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007569 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007570 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007571 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007572 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7573 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7574 // programmatically muted.
7575 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7576 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7577 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007578 bool exemptFromCapping =
7579 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7580 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007581 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7582 volumeSource, volumeDb);
7583 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007584 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7585 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7586 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007587 }
7588 }
Eric Laurente552edb2014-03-10 17:42:56 -07007589 // if a headset is connected, apply the following rules to ring tones and notifications
7590 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007591 // - always attenuate notifications volume by 6dB
7592 // - attenuate ring tones volume by 6dB unless music is not playing and
7593 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007594 // - if music is playing, always limit the volume to current music volume,
7595 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007596 if (!Intersection(deviceTypes,
7597 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7598 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007599 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7600 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007601 ((volumeSource == alarmVolumeSrc ||
7602 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007603 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7604 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7605 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007606 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7607 curves.canBeMuted()) {
7608
Eric Laurente552edb2014-03-10 17:42:56 -07007609 // when the phone is ringing we must consider that music could have been paused just before
7610 // by the music application and behave as if music was active if the last music track was
7611 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007612 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007613 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007614 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007615 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007616 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7617 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007618 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007619 float musicVolDb = computeVolume(musicCurves,
7620 musicVolumeSrc,
7621 musicCurves.getVolumeIndex(musicDevice),
7622 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007623 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7624 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7625 if (volumeDb > minVolDb) {
7626 volumeDb = minVolDb;
7627 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007628 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007629 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7630 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7631 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007632 // on A2DP, also ensure notification volume is not too low compared to media when
7633 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007634 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007635 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007636 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7637 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007638 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7639 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007640 }
7641 }
jiabin9a3361e2019-10-01 09:38:30 -07007642 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007643 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007644 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007645 }
7646 }
7647
François Gaffie43c73442018-11-08 08:21:55 +01007648 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007649}
7650
Eric Laurent3839bc02018-07-10 18:33:34 -07007651int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007652 VolumeSource fromVolumeSource,
7653 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007654{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007655 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007656 return srcIndex;
7657 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007658 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7659 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007660 float minSrc = (float)srcCurves.getVolumeIndexMin();
7661 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7662 float minDst = (float)dstCurves.getVolumeIndexMin();
7663 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007664
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007665 // preserve mute request or correct range
7666 if (srcIndex < minSrc) {
7667 if (srcIndex == 0) {
7668 return 0;
7669 }
7670 srcIndex = minSrc;
7671 } else if (srcIndex > maxSrc) {
7672 srcIndex = maxSrc;
7673 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007674 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7675}
7676
François Gaffieaaac0fd2018-11-22 17:56:39 +01007677status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7678 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007679 int index,
7680 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007681 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007682 int delayMs,
7683 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007684{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007685 // do not change actual attributes volume if the attributes is muted
7686 if (outputDesc->isMuted(volumeSource)) {
7687 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7688 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007689 return NO_ERROR;
7690 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007691 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7692 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7693 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7694 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007695
Eric Laurent2517af32020-11-25 15:31:27 +01007696 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007697 bool isHAUsed = isHearingAidUsedForComm();
7698
Eric Laurente552edb2014-03-10 17:42:56 -07007699 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007700 // if sco and call follow same curves, bypass forceUseForComm
7701 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007702 ((isVoiceVolSrc && isScoRequested) ||
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007703 (isBtScoVolSrc && !(isScoRequested || isHAUsed)))) {
Eric Laurent2517af32020-11-25 15:31:27 +01007704 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007705 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007706 // Do not return an error here as AudioService will always set both voice call
7707 // and bluetooth SCO volumes due to stream aliasing.
7708 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007709 }
jiabin9a3361e2019-10-01 09:38:30 -07007710 if (deviceTypes.empty()) {
7711 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007712 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007713
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007714 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7715 ALOGE("invalid volume index range");
7716 return BAD_VALUE;
7717 }
7718
jiabin9a3361e2019-10-01 09:38:30 -07007719 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7720 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007721 // Force VoIP volume to max for bluetooth SCO device except if muted
7722 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007723 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007724 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007725 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007726 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007727 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007728 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007729
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007730 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007731 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007732 // 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 +01007733 if (isVoiceVolSrc) {
7734 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007735 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007736 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007737 }
Eric Laurent18fba842016-03-31 14:41:26 -07007738 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007739 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7740 mLastVoiceVolume = voiceVolume;
7741 }
7742 }
Eric Laurente552edb2014-03-10 17:42:56 -07007743 return NO_ERROR;
7744}
7745
Eric Laurentc75307b2015-03-17 15:29:32 -07007746void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007747 const DeviceTypeSet& deviceTypes,
7748 int delayMs,
7749 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007750{
jiabincd510522020-01-22 09:40:55 -08007751 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007752 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7753 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7754 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007755 curves.getVolumeIndex(deviceTypes),
7756 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007757 }
7758}
7759
François Gaffiec005e562018-11-06 15:04:49 +01007760void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7761 bool on,
7762 const sp<AudioOutputDescriptor>& outputDesc,
7763 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007764 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007765{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007766 std::vector<VolumeSource> sourcesToMute;
7767 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7768 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7769 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007770 VolumeSource source = toVolumeSource(attributes, false);
7771 if ((source != VOLUME_SOURCE_NONE) &&
7772 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7773 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007774 sourcesToMute.push_back(source);
7775 }
Eric Laurente552edb2014-03-10 17:42:56 -07007776 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007777 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007778 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007779 }
7780
Eric Laurente552edb2014-03-10 17:42:56 -07007781}
7782
François Gaffieaaac0fd2018-11-22 17:56:39 +01007783void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7784 bool on,
7785 const sp<AudioOutputDescriptor>& outputDesc,
7786 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007787 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007788{
jiabin9a3361e2019-10-01 09:38:30 -07007789 if (deviceTypes.empty()) {
7790 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007791 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007792 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007793 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007794 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007795 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007796 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007797 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7798 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007799 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007800 }
7801 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007802 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7803 // ignored
7804 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007805 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007806 if (!outputDesc->isMuted(volumeSource)) {
7807 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007808 return;
7809 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007810 if (outputDesc->decMuteCount(volumeSource) == 0) {
7811 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007812 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007813 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007814 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007815 delayMs);
7816 }
7817 }
7818}
7819
François Gaffie53615e22015-03-19 09:24:12 +01007820bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7821{
François Gaffiec005e562018-11-06 15:04:49 +01007822 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007823 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7824 return true;
7825 }
7826
7827 // has known usage?
7828 switch (paa->usage) {
7829 case AUDIO_USAGE_UNKNOWN:
7830 case AUDIO_USAGE_MEDIA:
7831 case AUDIO_USAGE_VOICE_COMMUNICATION:
7832 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7833 case AUDIO_USAGE_ALARM:
7834 case AUDIO_USAGE_NOTIFICATION:
7835 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7836 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7837 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7838 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7839 case AUDIO_USAGE_NOTIFICATION_EVENT:
7840 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7841 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7842 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7843 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007844 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007845 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007846 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007847 case AUDIO_USAGE_EMERGENCY:
7848 case AUDIO_USAGE_SAFETY:
7849 case AUDIO_USAGE_VEHICLE_STATUS:
7850 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007851 break;
7852 default:
7853 return false;
7854 }
7855 return true;
7856}
7857
François Gaffie2110e042015-03-24 08:41:51 +01007858audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7859{
7860 return mEngine->getForceUse(usage);
7861}
7862
Eric Laurent96d1dda2022-03-14 17:14:19 +01007863bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007864 return isStateInCall(mEngine->getPhoneState());
7865}
7866
Eric Laurent96d1dda2022-03-14 17:14:19 +01007867bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007868 return is_state_in_call(state);
7869}
7870
Eric Laurentf9cccec2022-11-16 19:12:00 +01007871bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007872 audio_mode_t mode = mEngine->getPhoneState();
7873 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007874 || (mode == AUDIO_MODE_CALL_SCREEN)
7875 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007876}
7877
Eric Laurentf9cccec2022-11-16 19:12:00 +01007878bool AudioPolicyManager::isInCallOrScreening() const {
7879 audio_mode_t mode = mEngine->getPhoneState();
7880 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7881}
7882
Eric Laurentd60560a2015-04-10 11:31:20 -07007883void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7884{
7885 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007886 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007887 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007888 sourceDesc->sinkDevice()->equals(deviceDesc))
7889 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007890 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007891 }
7892 }
7893
7894 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7895 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7896 bool release = false;
7897 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7898 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7899 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7900 source->ext.device.type == deviceDesc->type()) {
7901 release = true;
7902 }
7903 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007904 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007905 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7906 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7907 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007908 sink->ext.device.type == deviceDesc->type() &&
7909 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7910 || strncmp(sink->ext.device.address, address,
7911 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007912 release = true;
7913 }
7914 }
7915 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007916 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7917 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007918 }
7919 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007920
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007921 mInputs.clearSessionRoutesForDevice(deviceDesc);
7922
Francois Gaffie716e1432019-01-14 16:58:59 +01007923 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007924}
7925
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007926void AudioPolicyManager::modifySurroundFormats(
7927 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007928 std::unordered_set<audio_format_t> enforcedSurround(
7929 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007930 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7931 for (const auto& pair : mConfig.getSurroundFormats()) {
7932 allSurround.insert(pair.first);
7933 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7934 }
Phil Burk09bc4612016-02-24 15:58:15 -08007935
7936 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7937 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007938 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007939 // This is the resulting set of formats depending on the surround mode:
7940 // 'all surround' = allSurround
7941 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7942 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7943 // 'manual surround' = mManualSurroundFormats
7944 // AUTO: formats v 'enforced surround'
7945 // ALWAYS: formats v 'all surround' v 'enforced surround'
7946 // NEVER: formats ^ 'non-surround'
7947 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007948
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007949 std::unordered_set<audio_format_t> formatSet;
7950 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7951 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007952 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007953 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007954 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007955 formatSet.insert(*formatIter);
7956 }
7957 }
7958 } else {
7959 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7960 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007961 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007962
jiabin81772902018-04-02 17:52:27 -07007963 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007964 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007965 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7966 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7967 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007968 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007969 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7970 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7971 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007972 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007973 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007974 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007975 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007976 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007977 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007978}
7979
jiabin06e4bab2019-07-29 10:13:34 -07007980void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7981 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007982 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7983 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7984
7985 // If NEVER, then remove support for channelMasks > stereo.
7986 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007987 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7988 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007989 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007990 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007991 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007992 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007993 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007994 }
7995 }
jiabin81772902018-04-02 17:52:27 -07007996 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7997 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7998 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007999 bool supports5dot1 = false;
8000 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008001 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008002 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8003 supports5dot1 = true;
8004 break;
8005 }
8006 }
8007 // If not then add 5.1 support.
8008 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008009 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008010 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008011 }
Phil Burk09bc4612016-02-24 15:58:15 -08008012 }
8013}
8014
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008015void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008016 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01008017 AudioProfileVector &profiles)
8018{
8019 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008020 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07008021
François Gaffie112b0af2015-11-19 16:13:25 +01008022 // Format MUST be checked first to update the list of AudioProfile
8023 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008024 reply = mpClientInterface->getParameters(
8025 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07008026 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008027 AudioParameter repliedParameters(reply);
8028 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008029 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01008030 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
8031 return;
8032 }
Phil Burk09bc4612016-02-24 15:58:15 -08008033 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01008034 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08008035 if (device == AUDIO_DEVICE_OUT_HDMI
8036 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008037 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07008038 }
jiabin3e277cc2019-09-10 14:27:34 -07008039 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01008040 }
François Gaffie112b0af2015-11-19 16:13:25 +01008041
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008042 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07008043 ChannelMaskSet channelMasks;
8044 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01008045 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07008046 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01008047
8048 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008049 reply = mpClientInterface->getParameters(
8050 ioHandle,
8051 requestedParameters.toString() + ";" +
8052 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01008053 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008054 AudioParameter repliedParameters(reply);
8055 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008056 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008057 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01008058 }
8059 }
8060 if (profiles.hasDynamicChannelsFor(format)) {
8061 reply = mpClientInterface->getParameters(ioHandle,
8062 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07008063 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01008064 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008065 AudioParameter repliedParameters(reply);
8066 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008067 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008068 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008069 if (device == AUDIO_DEVICE_OUT_HDMI
8070 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008071 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07008072 }
François Gaffie112b0af2015-11-19 16:13:25 +01008073 }
8074 }
jiabin3e277cc2019-09-10 14:27:34 -07008075 addDynamicAudioProfileAndSort(
8076 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01008077 }
8078}
Eric Laurentd60560a2015-04-10 11:31:20 -07008079
Mikhail Naganovdc769682018-05-04 15:34:08 -07008080status_t AudioPolicyManager::installPatch(const char *caller,
8081 audio_patch_handle_t *patchHandle,
8082 AudioIODescriptorInterface *ioDescriptor,
8083 const struct audio_patch *patch,
8084 int delayMs)
8085{
8086 ssize_t index = mAudioPatches.indexOfKey(
8087 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8088 *patchHandle : ioDescriptor->getPatchHandle());
8089 sp<AudioPatch> patchDesc;
8090 status_t status = installPatch(
8091 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8092 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008093 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008094 }
8095 return status;
8096}
8097
8098status_t AudioPolicyManager::installPatch(const char *caller,
8099 ssize_t index,
8100 audio_patch_handle_t *patchHandle,
8101 const struct audio_patch *patch,
8102 int delayMs,
8103 uid_t uid,
8104 sp<AudioPatch> *patchDescPtr)
8105{
8106 sp<AudioPatch> patchDesc;
8107 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8108 if (index >= 0) {
8109 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008110 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008111 }
8112
8113 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8114 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8115 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8116 if (status == NO_ERROR) {
8117 if (index < 0) {
8118 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008119 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008120 } else {
8121 patchDesc->mPatch = *patch;
8122 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008123 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008124 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008125 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008126 }
8127 nextAudioPortGeneration();
8128 mpClientInterface->onAudioPatchListUpdate();
8129 }
8130 if (patchDescPtr) *patchDescPtr = patchDesc;
8131 return status;
8132}
8133
jiabinbce0c1d2020-10-05 11:20:18 -07008134bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8135{
8136 const TrackClientVector activeClients = output->getActiveClients();
8137 if (activeClients.empty()) {
8138 return true;
8139 }
8140 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8141 if (index < 0) {
8142 ALOGE("%s, no audio patch found while there are active clients on output %d",
8143 __func__, output->getId());
8144 return false;
8145 }
8146 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8147 DeviceVector routedDevices;
8148 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8149 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8150 patchDesc->mPatch.sinks[i].id);
8151 if (device == nullptr) {
8152 ALOGE("%s, no audio device found with id(%d)",
8153 __func__, patchDesc->mPatch.sinks[i].id);
8154 return false;
8155 }
8156 routedDevices.add(device);
8157 }
8158 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008159 if (client->isInvalid()) {
8160 // No need to take care about invalidated clients.
8161 continue;
8162 }
jiabinbce0c1d2020-10-05 11:20:18 -07008163 sp<DeviceDescriptor> preferredDevice =
8164 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8165 if (mEngine->getOutputDevicesForAttributes(
8166 client->attributes(), preferredDevice, false) == routedDevices) {
8167 return false;
8168 }
8169 }
8170 return true;
8171}
8172
8173sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008174 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008175 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8176 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008177{
8178 for (const auto& device : devices) {
8179 // TODO: This should be checking if the profile supports the device combo.
8180 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008181 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8182 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008183 return nullptr;
8184 }
8185 }
8186 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8187 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008188 status_t status = desc->open(halConfig, mixerConfig, devices,
8189 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008190 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008191 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008192 return nullptr;
8193 }
8194
8195 // Here is where the out_set_parameters() for card & device gets called
8196 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8197 const audio_devices_t deviceType = device->type();
8198 const String8 &address = String8(device->address().c_str());
8199 if (!address.isEmpty()) {
8200 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8201 mpClientInterface->setParameters(output, String8(param));
8202 free(param);
8203 }
8204 updateAudioProfiles(device, output, profile->getAudioProfiles());
8205 if (!profile->hasValidAudioProfile()) {
8206 ALOGW("%s() missing param", __func__);
8207 desc->close();
8208 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008209 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8210 // Reopen the output with the best audio profile picked by APM when the profile supports
8211 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008212 desc->close();
8213 output = AUDIO_IO_HANDLE_NONE;
8214 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8215 profile->pickAudioProfile(
8216 config.sample_rate, config.channel_mask, config.format);
8217 config.offload_info.sample_rate = config.sample_rate;
8218 config.offload_info.channel_mask = config.channel_mask;
8219 config.offload_info.format = config.format;
8220
jiabina84c3d32022-12-02 18:59:55 +00008221 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008222 if (status != NO_ERROR) {
8223 return nullptr;
8224 }
8225 }
8226
8227 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008228
baek.kim -61c20122022-07-27 10:05:32 +00008229 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8230 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8231
jiabinbce0c1d2020-10-05 11:20:18 -07008232 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8233 sp<AudioPolicyMix> policyMix;
8234 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8235 policyMix->setOutput(desc);
8236 desc->mPolicyMix = policyMix;
8237 } else {
8238 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
8239 address.string());
8240 }
8241
baek.kim -61c20122022-07-27 10:05:32 +00008242 } else if (hasPrimaryOutput() && speaker != nullptr
8243 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008244 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8245 // no duplicated output for:
8246 // - direct outputs
8247 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008248 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008249 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8250
8251 //TODO: configure audio effect output stage here
8252
8253 // open a duplicating output thread for the new output and the primary output
8254 sp<SwAudioOutputDescriptor> dupOutputDesc =
8255 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8256 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8257 if (status == NO_ERROR) {
8258 // add duplicated output descriptor
8259 addOutput(duplicatedOutput, dupOutputDesc);
8260 } else {
8261 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8262 mPrimaryOutput->mIoHandle, output);
8263 desc->close();
8264 removeOutput(output);
8265 nextAudioPortGeneration();
8266 return nullptr;
8267 }
8268 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008269 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8270 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8271 mPrimaryOutput = desc;
8272 }
jiabinbce0c1d2020-10-05 11:20:18 -07008273 return desc;
8274}
8275
jiabinf1c73972022-04-14 16:28:52 -07008276status_t AudioPolicyManager::getDevicesForAttributes(
8277 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8278 // Devices are determined in the following precedence:
8279 //
8280 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8281 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8282 //
8283 // If no such dynamic policy then
8284 // 2) Devices containing an active client using setPreferredDevice
8285 // with same strategy as the attributes.
8286 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8287 //
8288 // If no corresponding active client with setPreferredDevice then
8289 // 3) Devices associated with the strategy determined by the attributes
8290 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8291 //
8292 // See related getOutputForAttrInt().
8293
8294 // check dynamic policies but only for primary descriptors (secondary not used for audible
8295 // audio routing, only used for duplication for playback capture)
8296 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008297 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008298 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008299 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8300 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8301 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008302 if (status != OK) {
8303 return status;
8304 }
8305
8306 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8307 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8308 // as they are unaffected by device/stream volume
8309 // (per SwAudioOutputDescriptor::isFixedVolume()).
8310 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8311 ) {
8312 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8313 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8314 devices.add(deviceDesc);
8315 } else {
8316 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8317 // which selects setPreferredDevice if active. This means forVolume call
8318 // will take an active setPreferredDevice, if such exists.
8319
8320 devices = mEngine->getOutputDevicesForAttributes(
8321 attr, nullptr /* preferredDevice */, false /* fromCache */);
8322 }
8323
8324 if (forVolume) {
8325 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8326 // for single volume control in AudioService (such relationship should exist if
8327 // SPEAKER_SAFE is present).
8328 //
8329 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8330 DeviceVector speakerSafeDevices =
8331 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8332 if (!speakerSafeDevices.isEmpty()) {
8333 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8334 devices.remove(speakerSafeDevices);
8335 }
8336 }
8337
8338 return NO_ERROR;
8339}
8340
8341status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8342 AudioProfileVector& audioProfiles,
8343 uint32_t flags,
8344 bool isInput) {
8345 for (const auto& hwModule : mHwModules) {
8346 // the MSD module checks for different conditions
8347 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8348 continue;
8349 }
8350 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8351 : hwModule->getOutputProfiles();
8352 for (const auto& profile : ioProfiles) {
8353 if (!profile->areAllDevicesSupported(devices) ||
8354 !profile->isCompatibleProfileForFlags(
8355 flags, false /*exactMatchRequiredForInputFlags*/)) {
8356 continue;
8357 }
8358 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8359 }
8360 }
8361
8362 if (!isInput) {
8363 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8364 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8365 if (msdModule != nullptr) {
8366 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8367 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8368 for (const auto &profile: msdModule->getOutputProfiles()) {
8369 if (!profile->asAudioPort()->isDirectOutput()) {
8370 continue;
8371 }
8372 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8373 }
8374 } else {
8375 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8376 }
8377 }
8378 }
8379
8380 return NO_ERROR;
8381}
8382
jiabin3ff8d7d2022-12-13 06:27:44 +00008383sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8384 const audio_config_t *config,
8385 audio_output_flags_t flags,
8386 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008387 closeOutput(outputDesc->mIoHandle);
8388 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8389 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8390 if (preferredOutput == nullptr) {
8391 ALOGE("%s failed to reopen output device=%d, caller=%s",
8392 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008393 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008394 return preferredOutput;
8395}
8396
8397void AudioPolicyManager::reopenOutputsWithDevices(
8398 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8399 for (const auto& [output, devices] : outputsToReopen) {
8400 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8401 closeOutput(output);
8402 openOutputWithProfileAndDevice(desc->mProfile, devices);
8403 }
jiabina84c3d32022-12-02 18:59:55 +00008404}
8405
jiabinc44b3462022-12-08 12:52:31 -08008406PortHandleVector AudioPolicyManager::getClientsForStream(
8407 audio_stream_type_t streamType) const {
8408 PortHandleVector clients;
8409 for (size_t i = 0; i < mOutputs.size(); ++i) {
8410 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8411 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8412 }
8413 return clients;
8414}
8415
8416void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8417 PortHandleVector clients;
8418 for (auto stream : streams) {
8419 PortHandleVector clientsForStream = getClientsForStream(stream);
8420 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8421 }
8422 mpClientInterface->invalidateTracks(clients);
8423}
8424
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008425} // namespace android