blob: 2fb6d586493a553fdd793997e3b6d8a2746b4f5a [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:
606 audioDeviceSet = getAudioDeviceOutAllBleSet();
607 break;
608 default:
609 ALOGE("%s() device type 0x%08x not supported", __func__, device);
610 return BAD_VALUE;
611 }
612
jiabin9a3361e2019-10-01 09:38:30 -0700613 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800614 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800615 for (const auto& device : declaredDevices) {
616 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800617 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800618 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800619 return status;
620}
621
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100622DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
623{
624 DeviceVector rxSinkdevices{};
625 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
626 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
627 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
628 auto rxSinkDevice = rxSinkdevices.itemAt(0);
629 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
630 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
631 // retrieve Rx Source device descriptor
632 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
633 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
634
635 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
636 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
637 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
638 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
639 return DeviceVector(rxSinkDevice);
640 }
641 }
642 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
643 // the device returned is not necessarily reachable via this output
644 // (filter later by setOutputDevices())
645 return getNewOutputDevices(mPrimaryOutput, fromCache);
646}
647
648status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
649{
650 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
651 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
652 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
653 }
654 return INVALID_OPERATION;
655}
656
657status_t AudioPolicyManager::updateCallRoutingInternal(
658 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700659{
660 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100661 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700662 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700663 if(!hasPrimaryOutput() ||
664 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100665 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700666 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100667 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100668
Francois Gaffie716e1432019-01-14 16:58:59 +0100669 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100670 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100671 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100672
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100673 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100674 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700675
Francois Gaffie601801d2021-06-22 13:27:39 +0200676 disconnectTelephonyAudioSource(mCallRxSourceClient);
677 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700678
François Gaffie9eb18552018-11-05 10:33:26 +0100679 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700680 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100681 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700682 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100683 // retrieve Rx Source and Tx Sink device descriptors
684 sp<DeviceDescriptor> rxSourceDevice =
685 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
686 String8(),
687 AUDIO_FORMAT_DEFAULT);
688 sp<DeviceDescriptor> txSinkDevice =
689 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
690 String8(),
691 AUDIO_FORMAT_DEFAULT);
692
693 // RX and TX Telephony device are declared by Primary Audio HAL
694 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
695 (telephonyRxModule->getHalVersionMajor() >= 3)) {
696 if (rxSourceDevice == 0 || txSinkDevice == 0) {
697 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100698 ALOGE("%s() no telephony Tx and/or RX device", __func__);
699 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100700 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100701 // createAudioPatchInternal now supports both HW / SW bridging
702 createRxPatch = true;
703 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100704 } else {
705 // If the RX device is on the primary HW module, then use legacy routing method for
706 // voice calls via setOutputDevice() on primary output.
707 // Otherwise, create two audio patches for TX and RX path.
708 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
709 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700710 // If the TX device is also on the primary HW module, setOutputDevice() will take care
711 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100712 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
713 (txSinkDevice != 0);
714 }
715 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
716 // Otherwise, create two audio patches for TX and RX path.
717 if (!createRxPatch) {
718 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700719 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200720 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800721 // If the TX device is on the primary HW module but RX device is
722 // on other HW module, SinkMetaData of telephony input should handle it
723 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700724 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700725 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100726 // terminate active capture if on the same HW module as the call TX source device
727 // FIXME: would be better to refine to only inputs whose profile connects to the
728 // call TX device but this information is not in the audio patch and logic here must be
729 // symmetric to the one in startInput()
730 for (const auto& activeDesc : mInputs.getActiveInputs()) {
731 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
732 closeActiveClients(activeDesc);
733 }
734 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200735 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800736 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100737 if (waitMs != nullptr) {
738 *waitMs = muteWaitMs;
739 }
740 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800741}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700742
Mikhail Naganov100f0122018-11-29 11:22:16 -0800743bool AudioPolicyManager::isDeviceOfModule(
744 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
745 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
746 if (module != 0) {
747 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
748 .indexOf(devDesc) != NAME_NOT_FOUND
749 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
750 .indexOf(devDesc) != NAME_NOT_FOUND;
751 }
752 return false;
753}
754
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200755void AudioPolicyManager::connectTelephonyRxAudioSource()
756{
Francois Gaffie601801d2021-06-22 13:27:39 +0200757 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200758 const struct audio_port_config source = {
759 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
760 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
761 };
762 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200763 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
764 ALOGE_IF(mCallRxSourceClient == nullptr,
765 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200766}
767
Francois Gaffie601801d2021-06-22 13:27:39 +0200768void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200769{
Francois Gaffie601801d2021-06-22 13:27:39 +0200770 if (clientDesc == nullptr) {
771 return;
772 }
773 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
774 "%s error stopping audio source", __func__);
775 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200776}
777
778void AudioPolicyManager::connectTelephonyTxAudioSource(
779 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
780 uint32_t delayMs)
781{
Francois Gaffie601801d2021-06-22 13:27:39 +0200782 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200783 if (srcDevice == nullptr || sinkDevice == nullptr) {
784 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
785 return;
786 }
787 PatchBuilder patchBuilder;
788 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
789 ALOGV("%s between source %s and sink %s", __func__,
790 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200791 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200792 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
793
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200794 struct audio_port_config source = {};
795 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200796 mCallTxSourceClient = new InternalSourceClientDescriptor(
797 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200798 mCommunnicationStrategy, toVolumeSource(aa));
799 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
800 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200801 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
802 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200803 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
804 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200805 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200806 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200807}
808
Eric Laurente0720872014-03-11 09:30:41 -0700809void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700810{
811 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100812 // store previous phone state for management of sonification strategy below
813 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100814 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100815
816 if (mEngine->setPhoneState(state) != NO_ERROR) {
817 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700818 return;
819 }
François Gaffie2110e042015-03-24 08:41:51 +0100820 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700821 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700822 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700823 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800824 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700825 }
826
François Gaffie2110e042015-03-24 08:41:51 +0100827 /**
828 * Switching to or from incall state or switching between telephony and VoIP lead to force
829 * routing command.
830 */
Eric Laurent74b71512019-11-06 17:21:57 -0800831 bool force = ((isStateInCall(oldState) != isStateInCall(state))
832 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700833
834 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700835 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700836
Eric Laurente552edb2014-03-10 17:42:56 -0700837 int delayMs = 0;
838 if (isStateInCall(state)) {
839 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100840 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
841 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700842 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700843 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700844 // mute media and sonification strategies and delay device switch by the largest
845 // latency of any output where either strategy is active.
846 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100847 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
848 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
849 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700850 (delayMs < (int)desc->latency()*2)) {
851 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700852 }
François Gaffiec005e562018-11-06 15:04:49 +0100853 setStrategyMute(musicStrategy, true, desc);
854 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
855 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
856 nullptr, true /*fromCache*/).types());
857 setStrategyMute(sonificationStrategy, true, desc);
858 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
859 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
860 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700861 }
862 }
863
Eric Laurent87ffa392015-05-22 10:32:38 -0700864 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700865 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100866 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700867 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100868 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
869 // force routing command to audio hardware when ending call
870 // even if no device change is needed
871 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
872 rxDevices = mPrimaryOutput->devices();
873 }
874 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200875 disconnectTelephonyAudioSource(mCallRxSourceClient);
876 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100877 }
François Gaffie11d30102018-11-02 16:09:09 +0100878 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700879 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700880 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700881
jiabin3ff8d7d2022-12-13 06:27:44 +0000882 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700883 // reevaluate routing on all outputs in case tracks have been started during the call
884 for (size_t i = 0; i < mOutputs.size(); i++) {
885 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100886 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200887 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
888 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000889 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
890 // If the device is using preferred mixer attributes, the output need to reopen
891 // with default configuration when the new selected devices are different from
892 // current routing devices.
893 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
894 continue;
895 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200896 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
897 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700898 }
899 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000900 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700901
Eric Laurent96d1dda2022-03-14 17:14:19 +0100902 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
903
Eric Laurente552edb2014-03-10 17:42:56 -0700904 if (isStateInCall(state)) {
905 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700906 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800907 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700908 }
909
910 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100911 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
912 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700913}
914
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700915audio_mode_t AudioPolicyManager::getPhoneState() {
916 return mEngine->getPhoneState();
917}
918
Eric Laurente0720872014-03-11 09:30:41 -0700919void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100920 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700921{
François Gaffie2110e042015-03-24 08:41:51 +0100922 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700923 if (config == mEngine->getForceUse(usage)) {
924 return;
925 }
Eric Laurente552edb2014-03-10 17:42:56 -0700926
François Gaffie2110e042015-03-24 08:41:51 +0100927 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
928 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
929 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700930 }
François Gaffie2110e042015-03-24 08:41:51 +0100931 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
932 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
933 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700934
935 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700936 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800937
Eric Laurent22fcda22019-05-17 16:28:47 -0700938 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
939 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800940 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700941 }
942
Eric Laurentdc462862016-07-19 12:29:53 -0700943 //FIXME: workaround for truncated touch sounds
944 // to be removed when the problem is handled by system UI
945 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700946 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
947 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
948 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700949
950 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100951 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700952}
953
Eric Laurente0720872014-03-11 09:30:41 -0700954void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700955{
956 ALOGV("setSystemProperty() property %s, value %s", property, value);
957}
958
Dorin Drimusecc9f422022-03-09 17:57:40 +0100959// Find an MSD output profile compatible with the parameters passed.
960// When "directOnly" is set, restrict search to profiles for direct outputs.
961sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
962 const DeviceVector& devices,
963 uint32_t samplingRate,
964 audio_format_t format,
965 audio_channel_mask_t channelMask,
966 audio_output_flags_t flags,
967 bool directOnly)
968{
969 flags = getRelevantFlags(flags, directOnly);
970
971 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
972 if (msdModule != nullptr) {
973 // for the msd module check if there are patches to the output devices
974 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
975 HwModuleCollection modules;
976 modules.add(msdModule);
977 return searchCompatibleProfileHwModules(
978 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
979 flags, directOnly);
980 }
981 }
982 return nullptr;
983}
984
Michael Chana94fbb22018-04-24 14:31:19 +1000985// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
986// search to profiles for direct outputs.
987sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100988 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000989 uint32_t samplingRate,
990 audio_format_t format,
991 audio_channel_mask_t channelMask,
992 audio_output_flags_t flags,
993 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700994{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100995 flags = getRelevantFlags(flags, directOnly);
996
997 return searchCompatibleProfileHwModules(
998 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
999}
1000
1001audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1002 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001003 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001004 // only retain flags that will drive the direct output profile selection
1005 // if explicitly requested
1006 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001007 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001008 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1009 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001010 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001011 return flags;
1012}
Eric Laurent861a6282015-05-18 15:40:16 -07001013
Dorin Drimusecc9f422022-03-09 17:57:40 +01001014sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1015 const HwModuleCollection& hwModules,
1016 const DeviceVector& devices,
1017 uint32_t samplingRate,
1018 audio_format_t format,
1019 audio_channel_mask_t channelMask,
1020 audio_output_flags_t flags,
1021 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001022 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001023 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001024 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001025 if (!curProfile->isCompatibleProfile(devices,
1026 samplingRate, NULL /*updatedSamplingRate*/,
1027 format, NULL /*updatedFormat*/,
1028 channelMask, NULL /*updatedChannelMask*/,
1029 flags)) {
1030 continue;
1031 }
1032 // reject profiles not corresponding to a device currently available
1033 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1034 continue;
1035 }
1036 // reject profiles if connected device does not support codec
1037 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1038 continue;
1039 }
1040 if (!directOnly) {
1041 return curProfile;
1042 }
1043
1044 // when searching for direct outputs, if several profiles are compatible, give priority
1045 // to one with offload capability
1046 if (profile != 0 &&
1047 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001048 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001049 }
1050 profile = curProfile;
1051 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1052 break;
1053 }
Eric Laurente552edb2014-03-10 17:42:56 -07001054 }
1055 }
Eric Laurent861a6282015-05-18 15:40:16 -07001056 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001057}
1058
Eric Laurentfa0f6742021-08-17 18:39:44 +02001059sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001060 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001061{
1062 for (const auto& hwModule : mHwModules) {
1063 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001064 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001065 continue;
1066 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001067 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001068 // reject profiles not corresponding to a device currently available
1069 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1070 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1071 continue;
1072 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001073 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1074 != devices.size()) {
1075 continue;
1076 }
1077 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001078 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1079 return curProfile;
1080 }
1081 }
1082 return nullptr;
1083}
1084
Eric Laurentf4e63452017-11-06 19:31:46 +00001085audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001086{
François Gaffiec005e562018-11-06 15:04:49 +01001087 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001088
1089 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1090 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1091 // format, flags, etc. This may result in some discrepancy for functions that utilize
1092 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1093 // and AudioSystem::getOutputSamplingRate().
1094
François Gaffie11d30102018-11-02 16:09:09 +01001095 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001096 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001097
François Gaffie11d30102018-11-02 16:09:09 +01001098 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1099 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001100 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001101}
1102
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001103status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1104 const audio_attributes_t *srcAttr,
1105 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001106{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001107 if (srcAttr != NULL) {
1108 if (!isValidAttributes(srcAttr)) {
1109 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1110 __func__,
1111 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1112 srcAttr->tags);
1113 return BAD_VALUE;
1114 }
1115 *dstAttr = *srcAttr;
1116 } else {
1117 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1118 ALOGE("%s: invalid stream type", __func__);
1119 return BAD_VALUE;
1120 }
François Gaffiec005e562018-11-06 15:04:49 +01001121 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001122 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001123
1124 // Only honor audibility enforced when required. The client will be
1125 // forced to reconnect if the forced usage changes.
1126 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001127 dstAttr->flags = static_cast<audio_flags_mask_t>(
1128 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001129 }
1130
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001131 return NO_ERROR;
1132}
1133
Kevin Rocard153f92d2018-12-18 18:33:28 -08001134status_t AudioPolicyManager::getOutputForAttrInt(
1135 audio_attributes_t *resultAttr,
1136 audio_io_handle_t *output,
1137 audio_session_t session,
1138 const audio_attributes_t *attr,
1139 audio_stream_type_t *stream,
1140 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001141 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001142 audio_output_flags_t *flags,
1143 audio_port_handle_t *selectedDeviceId,
1144 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001145 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001146 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001147 bool *isSpatialized,
1148 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001149{
François Gaffiec005e562018-11-06 15:04:49 +01001150 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001151 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001152 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001153 const sp<DeviceDescriptor> requestedDevice =
1154 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1155
Eric Laurent8a1095a2019-11-08 14:44:16 -08001156 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001157 *isSpatialized = false;
1158
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001159 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1160 if (status != NO_ERROR) {
1161 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001162 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001163 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001164 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001165 }
François Gaffiec005e562018-11-06 15:04:49 +01001166 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001167
François Gaffiec005e562018-11-06 15:04:49 +01001168 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1169 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001170
Kevin Rocard153f92d2018-12-18 18:33:28 -08001171 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1172 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1173 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001174 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001175 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1176 .channel_mask = config->channel_mask,
1177 .format = config->format,
1178 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001179 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
1180 primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001181 if (status != OK) {
1182 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001183 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001184
Kevin Rocard153f92d2018-12-18 18:33:28 -08001185 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001186 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001187
1188 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001189 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1190 && !audio_is_linear_pcm(config->format)) {
1191 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001192 return BAD_VALUE;
1193 }
1194 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001195 sp<DeviceDescriptor> deviceDesc =
1196 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1197 primaryMix->mDeviceAddress,
1198 AUDIO_FORMAT_DEFAULT);
1199 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001200 bool tryDirectForFlags = policyDesc == nullptr ||
1201 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1202 // if a direct output can be opened to deliver the track's multi-channel content to the
1203 // output rather than being downmixed by the primary output, then use this direct
1204 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1205 // mix.
1206 bool tryDirectForChannelMask = policyDesc != nullptr
1207 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1208 audio_channel_count_from_out_mask(config->channel_mask));
1209 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001210 audio_io_handle_t newOutput;
1211 status = openDirectOutput(
1212 *stream, session, config,
1213 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1214 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001215 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001216 policyDesc = mOutputs.valueFor(newOutput);
1217 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001218 } else if (tryDirectForFlags) {
1219 policyDesc = nullptr;
1220 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001221 }
1222 if (policyDesc != nullptr) {
1223 policyDesc->mPolicyMix = primaryMix;
1224 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001225 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001226
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001227 ALOGV("getOutputForAttr() returns output %d", *output);
1228 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1229 *outputType = API_OUT_MIX_PLAYBACK;
1230 } else {
1231 *outputType = API_OUTPUT_LEGACY;
1232 }
1233 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001234 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001235 }
François Gaffiec005e562018-11-06 15:04:49 +01001236 // Virtual sources must always be dynamicaly or explicitly routed
1237 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1238 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1239 return BAD_VALUE;
1240 }
1241 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1242 // in order to let the choice of the order to future vendor engine
1243 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001244
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001245 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001246 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001247 }
1248
Nadav Barb2f18162018-07-18 13:01:53 +03001249 // Set incall music only if device was explicitly set, and fallback to the device which is
1250 // chosen by the engine if not.
1251 // FIXME: provide a more generic approach which is not device specific and move this back
1252 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001253 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001254 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001255 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001256 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001257 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001258 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001259 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001260 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001261 }
1262 }
1263
François Gaffiec005e562018-11-06 15:04:49 +01001264 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1265 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1266 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001267
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001268 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001269 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001270 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001271 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001272 ALOGV("%s() Using MSD devices %s instead of devices %s",
1273 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001274 } else {
1275 *output = AUDIO_IO_HANDLE_NONE;
1276 }
1277 }
1278 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001279 sp<PreferredMixerAttributesInfo> info = nullptr;
1280 if (outputDevices.size() == 1) {
1281 info = getPreferredMixerAttributesInfo(
1282 outputDevices.itemAt(0)->getId(),
1283 mEngine->getProductStrategyForAttributes(*resultAttr));
1284 if (info != nullptr && info->getUid() != uid && info->getActiveClientCount() == 0) {
1285 // Only use preferred mixer when the requested uid matched or
1286 // there is active client on preferred mixer.
1287 info = nullptr;
1288 }
1289 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001290 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001291 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabinc658e452022-10-21 20:52:21 +00001292 *isBitPerfect = (info != nullptr
1293 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
1294 && *output != AUDIO_IO_HANDLE_NONE);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001295 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001296 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001297 AudioProfileVector profiles;
1298 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1299 if (ret == NO_ERROR && !profiles.empty()) {
1300 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
1301 : *profiles[0]->getChannels().begin();
1302 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
1303 : *profiles[0]->getSampleRates().begin();
1304 config->format = profiles[0]->getFormat();
1305 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001306 return INVALID_OPERATION;
1307 }
Paul McLeanaa981192015-03-21 09:55:15 -07001308
François Gaffiec005e562018-11-06 15:04:49 +01001309 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001310 for (auto &outputDevice : outputDevices) {
1311 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1312 *selectedDeviceId = outputDevice->getId();
1313 break;
1314 }
1315 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001316
Eric Laurent8a1095a2019-11-08 14:44:16 -08001317 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1318 *outputType = API_OUTPUT_TELEPHONY_TX;
1319 } else {
1320 *outputType = API_OUTPUT_LEGACY;
1321 }
1322
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001323 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1324
1325 return NO_ERROR;
1326}
1327
1328status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1329 audio_io_handle_t *output,
1330 audio_session_t session,
1331 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001332 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001333 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001334 audio_output_flags_t *flags,
1335 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001336 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001337 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001338 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001339 bool *isSpatialized,
1340 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001341{
1342 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1343 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1344 return INVALID_OPERATION;
1345 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001346 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001347 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001348 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001349 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001350 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001351 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001352 const sp<DeviceDescriptor> requestedDevice =
1353 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1354
1355 // Prevent from storing invalid requested device id in clients
1356 const audio_port_handle_t sanitizedRequestedPortId =
1357 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1358 *selectedDeviceId = sanitizedRequestedPortId;
1359
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001360 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001361 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001362 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1363 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001364 if (status != NO_ERROR) {
1365 return status;
1366 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001367 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001368 if (secondaryOutputs != nullptr) {
1369 for (auto &secondaryMix : secondaryMixes) {
1370 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1371 if (outputDesc != nullptr &&
1372 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1373 secondaryOutputs->push_back(outputDesc->mIoHandle);
1374 weakSecondaryOutputDescs.push_back(outputDesc);
1375 }
1376 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001377 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001378
Eric Laurent8fc147b2018-07-22 19:13:55 -07001379 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001380 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001381 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001382 };
jiabin4ef93452019-09-10 14:29:54 -07001383 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001384
Eric Laurentc209fe42020-06-05 18:11:23 -07001385 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001386 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001387 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001388 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001389 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001390 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001391 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001392 std::move(weakSecondaryOutputDescs),
1393 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001394 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001395
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001396 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1397 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001398
Eric Laurente83b55d2014-11-14 10:06:21 -08001399 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001400}
1401
Eric Laurentc529cf62020-04-17 18:19:10 -07001402status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1403 audio_session_t session,
1404 const audio_config_t *config,
1405 audio_output_flags_t flags,
1406 const DeviceVector &devices,
1407 audio_io_handle_t *output) {
1408
1409 *output = AUDIO_IO_HANDLE_NONE;
1410
1411 // skip direct output selection if the request can obviously be attached to a mixed output
1412 // and not explicitly requested
1413 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1414 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1415 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1416 return NAME_NOT_FOUND;
1417 }
1418
1419 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1420 // This prevents creating an offloaded track and tearing it down immediately after start
1421 // when audioflinger detects there is an active non offloadable effect.
1422 // FIXME: We should check the audio session here but we do not have it in this context.
1423 // This may prevent offloading in rare situations where effects are left active by apps
1424 // in the background.
1425 sp<IOProfile> profile;
1426 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1427 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1428 profile = getProfileForOutput(
1429 devices, config->sample_rate, config->format, config->channel_mask,
1430 flags, true /* directOnly */);
1431 }
1432
1433 if (profile == nullptr) {
1434 return NAME_NOT_FOUND;
1435 }
1436
1437 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1438 for (size_t i = 0; i < mOutputs.size(); i++) {
1439 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1440 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1441 // reuse direct output if currently open by the same client
1442 // and configured with same parameters
1443 if ((config->sample_rate == desc->getSamplingRate()) &&
1444 (config->format == desc->getFormat()) &&
1445 (config->channel_mask == desc->getChannelMask()) &&
1446 (session == desc->mDirectClientSession)) {
1447 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001448 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001449 mOutputs.keyAt(i), session);
1450 *output = mOutputs.keyAt(i);
1451 return NO_ERROR;
1452 }
1453 }
1454 }
1455
1456 if (!profile->canOpenNewIo()) {
1457 return NAME_NOT_FOUND;
1458 }
1459
1460 sp<SwAudioOutputDescriptor> outputDesc =
1461 new SwAudioOutputDescriptor(profile, mpClientInterface);
1462
Michael Chan6fb34492020-12-08 15:44:49 +11001463 // An MSD patch may be using the only output stream that can service this request. Release
1464 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001465 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001466
Eric Laurentf1f22e72021-07-13 14:04:14 +02001467 status_t status =
1468 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001469
1470 // only accept an output with the requested parameters
1471 if (status != NO_ERROR ||
1472 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1473 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1474 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1475 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1476 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1477 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1478 config->channel_mask, outputDesc->getChannelMask());
1479 if (*output != AUDIO_IO_HANDLE_NONE) {
1480 outputDesc->close();
1481 }
1482 // fall back to mixer output if possible when the direct output could not be open
1483 if (audio_is_linear_pcm(config->format) &&
1484 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1485 return NAME_NOT_FOUND;
1486 }
1487 *output = AUDIO_IO_HANDLE_NONE;
1488 return BAD_VALUE;
1489 }
1490 outputDesc->mDirectOpenCount = 1;
1491 outputDesc->mDirectClientSession = session;
1492
1493 addOutput(*output, outputDesc);
1494 mPreviousOutputs = mOutputs;
1495 ALOGV("%s returns new direct output %d", __func__, *output);
1496 mpClientInterface->onAudioPortListUpdate();
1497 return NO_ERROR;
1498}
1499
François Gaffie11d30102018-11-02 16:09:09 +01001500audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1501 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001502 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001503 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001504 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001505 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001506 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001507 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001508 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001509{
Andy Hungc88b0642018-04-27 15:42:35 -07001510 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001511
jiabine375d412019-02-26 12:54:53 -08001512 // Discard haptic channel mask when forcing muting haptic channels.
1513 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001514 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1515 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001516
Eric Laurente552edb2014-03-10 17:42:56 -07001517 // open a direct output if required by specified parameters
1518 //force direct flag if offload flag is set: offloading implies a direct output stream
1519 // and all common behaviors are driven by checking only the direct flag
1520 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001521 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1522 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001523 }
Nadav Bar766fb022018-01-07 12:18:03 +02001524 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1525 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001526 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001527
1528 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1529
Eric Laurente83b55d2014-11-14 10:06:21 -08001530 // only allow deep buffering for music stream type
1531 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001532 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001533 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001534 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001535 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1536 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001537 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001538 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001539 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001540 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001541 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001542 audio_is_linear_pcm(config->format) &&
1543 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001544 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001545 AUDIO_OUTPUT_FLAG_DIRECT);
1546 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001547 }
Eric Laurente552edb2014-03-10 17:42:56 -07001548
Carter Hsua3abb402021-10-26 11:11:20 +08001549 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1550 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1551 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1552 }
1553
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001554 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001555 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001556 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001557 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001558 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001559 }
1560
Eric Laurentc529cf62020-04-17 18:19:10 -07001561 audio_config_t directConfig = *config;
1562 directConfig.channel_mask = channelMask;
1563 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1564 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001565 return output;
1566 }
1567
Eric Laurent14cbfca2016-03-17 09:42:16 -07001568 // A request for HW A/V sync cannot fallback to a mixed output because time
1569 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001570 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001571 return AUDIO_IO_HANDLE_NONE;
1572 }
1573
Eric Laurente552edb2014-03-10 17:42:56 -07001574 // ignoring channel mask due to downmix capability in mixer
1575
1576 // open a non direct output
1577
1578 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001579 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001580 // get which output is suitable for the specified stream. The actual
1581 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001582 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001583 if (prefMixerConfigInfo != nullptr) {
1584 for (audio_io_handle_t outputHandle : outputs) {
1585 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1586 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1587 output = outputHandle;
1588 break;
1589 }
1590 }
1591 if (output == AUDIO_IO_HANDLE_NONE) {
1592 // No output open with the preferred profile. Open a new one.
1593 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1594 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1595 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1596 config.format = prefMixerConfigInfo->getConfigBase().format;
1597 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1598 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1599 &config, prefMixerConfigInfo->getFlags());
1600 if (preferredOutput == nullptr) {
1601 ALOGE("%s failed to open output with preferred mixer config", __func__);
1602 } else {
1603 output = preferredOutput->mIoHandle;
1604 }
1605 }
1606 } else {
1607 // at this stage we should ignore the DIRECT flag as no direct output could be
1608 // found earlier
1609 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1610 output = selectOutput(
1611 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1612 }
Eric Laurente552edb2014-03-10 17:42:56 -07001613 }
François Gaffie11d30102018-11-02 16:09:09 +01001614 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001615 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001616 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001617
Eric Laurente552edb2014-03-10 17:42:56 -07001618 return output;
1619}
1620
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001621sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001622 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1623 mAvailableInputDevices);
1624 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1625}
1626
1627DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1628 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1629 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001630}
1631
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001632const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001633 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001634 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1635 if (msdModule != 0) {
1636 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1637 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1638 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1639 const struct audio_port_config *source = &patch->mPatch.sources[j];
1640 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1641 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001642 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001643 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001644 }
1645 }
1646 }
1647 return msdPatches;
1648}
1649
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001650bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1651 ssize_t index = mAudioPatches.indexOfKey(handle);
1652 if (index < 0) {
1653 return false;
1654 }
1655 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1656 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1657 if (msdModule == nullptr) {
1658 return false;
1659 }
1660 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1661 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1662 return true;
1663 }
1664 index = getMsdOutputPatches().indexOfKey(handle);
1665 if (index < 0) {
1666 return false;
1667 }
1668 return true;
1669}
1670
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001671status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1672 const InputProfileCollection &inputProfiles,
1673 const OutputProfileCollection &outputProfiles,
1674 const sp<DeviceDescriptor> &sourceDevice,
1675 const sp<DeviceDescriptor> &sinkDevice,
1676 AudioProfileVector& sourceProfiles,
1677 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001678 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001679 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001680 return NO_INIT;
1681 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001682 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001683 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001684 return NO_INIT;
1685 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001686 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001687 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1688 inProfile->supportsDevice(sourceDevice)) {
1689 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001690 }
1691 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001692 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001693 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001694 outProfile->supportsDevice(sinkDevice)) {
1695 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001696 }
1697 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001698 return NO_ERROR;
1699}
1700
1701status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1702 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1703 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1704{
Dean Wheatley16809da2022-12-09 14:55:46 +11001705 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1706 static const std::vector<audio_format_t> formatsOrder = {{
1707 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1708 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1709 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1710 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1711 // preferred).
1712 std::vector<audio_channel_mask_t> masks = {{
1713 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1714 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1715 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1716 // insert index masks (higher counts most preferred) as preferred over position masks
1717 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1718 masks.insert(
1719 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1720 }
1721 return masks;
1722 }();
1723
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001724 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001725 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1726 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001727 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001728 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1729 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001730 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001731 }
1732 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1733 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1734 sinkConfig->format = bestSinkConfig.format;
1735 // For encoded streams force direct flag to prevent downstream mixing.
1736 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1737 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001738 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1739 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001740 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001741 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1742 // raw and IEC61937 framed streams.
1743 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1744 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1745 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001746 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1747 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001748 sourceConfig->channel_mask =
1749 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1750 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1751 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001752 sourceConfig->format = bestSinkConfig.format;
1753 // Copy input stream directly without any processing (e.g. resampling).
1754 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1755 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1756 if (hwAvSync) {
1757 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1758 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1759 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1760 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1761 }
1762 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1763 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1764 sinkConfig->config_mask |= config_mask;
1765 sourceConfig->config_mask |= config_mask;
1766 return NO_ERROR;
1767}
1768
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001769PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1770 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001771{
1772 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001773 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1774 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1775 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1776 if (deviceModule == nullptr) {
1777 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1778 return patchBuilder;
1779 }
1780 const InputProfileCollection inputProfiles = msdIsSource ?
1781 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1782 const OutputProfileCollection outputProfiles = msdIsSource ?
1783 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1784
1785 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1786 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1787 device : getMsdAudioOutDevices().itemAt(0);
1788 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1789
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001790 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1791 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001792 AudioProfileVector sourceProfiles;
1793 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001794 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1795 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001796 for (auto hwAvSync : { true, false }) {
1797 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1798 sourceProfiles, sinkProfiles) != NO_ERROR) {
1799 continue;
1800 }
1801 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1802 &sinkConfig) == NO_ERROR) {
1803 // Found a matching config. Re-create PatchBuilder with this config.
1804 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1805 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001806 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001807 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001808 " supporting PCM format conversion.", __func__);
1809 return patchBuilder;
1810}
1811
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001812status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001813 DeviceVector devices;
1814 if (outputDevices != nullptr && outputDevices->size() > 0) {
1815 devices.add(*outputDevices);
1816 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001817 // Use media strategy for unspecified output device. This should only
1818 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1819 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001820 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001821 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001822 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001823 }
Michael Chan6fb34492020-12-08 15:44:49 +11001824 std::vector<PatchBuilder> patchesToCreate;
1825 for (auto i = 0u; i < devices.size(); ++i) {
1826 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001827 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001828 }
1829 // Retain only the MSD patches associated with outputDevices request.
1830 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001831 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001832 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1833 auto retainedPatch = false;
1834 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1835 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1836 patchesToRemove.removeItemsAt(i);
1837 retainedPatch = true;
1838 break;
1839 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001840 }
Michael Chan6fb34492020-12-08 15:44:49 +11001841 if (retainedPatch) {
1842 it = patchesToCreate.erase(it);
1843 continue;
1844 }
1845 ++it;
1846 }
1847 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1848 return NO_ERROR;
1849 }
1850 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1851 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001852 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001853 }
Michael Chan6fb34492020-12-08 15:44:49 +11001854 status_t status = NO_ERROR;
1855 for (const auto &p : patchesToCreate) {
1856 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1857 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1858 char message[256];
1859 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1860 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1861 currStatus == NO_ERROR ? "Success" : "Error",
1862 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1863 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1864 if (currStatus == NO_ERROR) {
1865 ALOGD("%s", message);
1866 } else {
1867 ALOGE("%s", message);
1868 if (status == NO_ERROR) {
1869 status = currStatus;
1870 }
1871 }
1872 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001873 return status;
1874}
1875
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001876void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1877 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001878 for (size_t i = 0; i < msdPatches.size(); i++) {
1879 const auto& patch = msdPatches[i];
1880 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1881 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1882 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1883 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1884 releaseAudioPatch(patch->getHandle(), mUidCached);
1885 break;
1886 }
1887 }
1888 }
1889}
1890
Dorin Drimus94d94412022-02-02 09:05:02 +01001891bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1892 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1893 AudioPatchCollection msdPatches = getMsdOutputPatches();
1894 for (size_t i = 0; i < msdPatches.size(); i++) {
1895 const auto& patch = msdPatches[i];
1896 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1897 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1898 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1899 const auto& foundDevice = devicesToCheck.getDevice(
1900 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1901 if (foundDevice != nullptr) {
1902 devicesToCheck.remove(foundDevice);
1903 if (devicesToCheck.isEmpty()) {
1904 return true;
1905 }
1906 }
1907 }
1908 }
1909 }
1910 return false;
1911}
1912
Eric Laurente0720872014-03-11 09:30:41 -07001913audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001914 audio_output_flags_t flags,
1915 audio_format_t format,
1916 audio_channel_mask_t channelMask,
1917 uint32_t samplingRate,
1918 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001919{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001920 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1921 "%s called with format %#x", __func__, format);
1922
jiabinebb6af42020-06-09 17:31:17 -07001923 // Return the output that haptic-generating attached to when 1) session id is specified,
1924 // 2) haptic-generating effect exists for given session id and 3) the output that
1925 // haptic-generating effect attached to is in given outputs.
1926 if (sessionId != AUDIO_SESSION_NONE) {
1927 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1928 sessionId, FX_IID_HAPTICGENERATOR);
1929 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1930 return hapticGeneratingOutput;
1931 }
1932 }
1933
Eric Laurent16c66dd2019-05-01 17:54:10 -07001934 // Flags disqualifying an output: the match must happen before calling selectOutput()
1935 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1936 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1937
1938 // Flags expressing a functional request: must be honored in priority over
1939 // other criteria
1940 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1941 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001942 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1943 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001944 // Flags expressing a performance request: have lower priority than serving
1945 // requested sampling rate or channel mask
1946 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1947 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1948 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1949
1950 const audio_output_flags_t functionalFlags =
1951 (audio_output_flags_t)(flags & kFunctionalFlags);
1952 const audio_output_flags_t performanceFlags =
1953 (audio_output_flags_t)(flags & kPerformanceFlags);
1954
1955 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1956
Eric Laurente552edb2014-03-10 17:42:56 -07001957 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001958 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001959 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001960 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001961 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001962 // with tiebreak preferring the minimum number of extra functional flags
1963 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001964 // 3: the output supporting the exact channel mask
1965 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00001966 // 5: the output with the highest sampling rate if the requested sample rate is
1967 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001968 // 6: the output with the highest number of requested performance flags
1969 // 7: the output with the bit depth the closest to the requested one
1970 // 8: the primary output
1971 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001972
Eric Laurent16c66dd2019-05-01 17:54:10 -07001973 // matching criteria values in priority order for best matching output so far
1974 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001975
Eric Laurent16c66dd2019-05-01 17:54:10 -07001976 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1977 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1978 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001979
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001980 for (audio_io_handle_t output : outputs) {
1981 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001982 // matching criteria values in priority order for current output
1983 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001984
Eric Laurent16c66dd2019-05-01 17:54:10 -07001985 if (outputDesc->isDuplicated()) {
1986 continue;
1987 }
1988 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1989 continue;
1990 }
Eric Laurent8838a382014-09-08 16:44:28 -07001991
Eric Laurent16c66dd2019-05-01 17:54:10 -07001992 // If haptic channel is specified, use the haptic output if present.
1993 // When using haptic output, same audio format and sample rate are required.
1994 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001995 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001996 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1997 continue;
1998 }
1999 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002000 && format == outputDesc->getFormat()
2001 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002002 currentMatchCriteria[0] = outputHapticChannelCount;
2003 }
2004
2005 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002006 const int matchingFunctionalFlags =
2007 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2008 const int totalFunctionalFlags =
2009 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2010 // Prefer matching functional flags, but subtract unnecessary functional flags.
2011 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002012
2013 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002014 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2015 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002016 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2017 channelCount <= outputChannelCount) {
2018 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002019 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2020 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002021 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002022 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002023 currentMatchCriteria[3] = outputChannelCount;
2024 }
2025
2026 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002027 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002028 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002029 }
2030
2031 // performance flags match
2032 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2033
2034 // format match
2035 if (format != AUDIO_FORMAT_INVALID) {
2036 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002037 PolicyAudioPort::kFormatDistanceMax -
2038 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002039 }
2040
2041 // primary output match
2042 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2043
2044 // compare match criteria by priority then value
2045 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2046 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2047 bestMatchCriteria = currentMatchCriteria;
2048 bestOutput = output;
2049
2050 std::stringstream result;
2051 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2052 std::ostream_iterator<int>(result, " "));
2053 ALOGV("%s new bestOutput %d criteria %s",
2054 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002055 }
2056 }
2057
Eric Laurent16c66dd2019-05-01 17:54:10 -07002058 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002059}
2060
Eric Laurent8fc147b2018-07-22 19:13:55 -07002061status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002062{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002063 ALOGV("%s portId %d", __FUNCTION__, portId);
2064
2065 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2066 if (outputDesc == 0) {
2067 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002068 return BAD_VALUE;
2069 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002070 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002071
Eric Laurent8fc147b2018-07-22 19:13:55 -07002072 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002073 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002074
Eric Laurent733ce942017-12-07 12:18:25 -08002075 status_t status = outputDesc->start();
2076 if (status != NO_ERROR) {
2077 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002078 }
2079
Eric Laurent97ac8712018-07-27 18:59:02 -07002080 uint32_t delayMs;
2081 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002082
2083 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002084 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002085 if (status == DEAD_OBJECT) {
2086 sp<SwAudioOutputDescriptor> desc =
2087 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2088 if (desc == nullptr) {
2089 // This is not common, it may indicate something wrong with the HAL.
2090 ALOGE("%s unable to open output with default config", __func__);
2091 return status;
2092 }
2093 desc->mUsePreferredMixerAttributes = true;
2094 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002095 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002096 }
jiabina84c3d32022-12-02 18:59:55 +00002097
2098 // If the client is the first one active on preferred mixer parameters, reopen the output
2099 // if the current mixer parameters doesn't match the preferred one.
2100 if (outputDesc->devices().size() == 1) {
2101 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2102 outputDesc->devices()[0]->getId(), client->strategy());
2103 if (info != nullptr && info->getUid() == client->uid()) {
2104 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2105 info->getConfigBase(), info->getFlags())) {
2106 stopSource(outputDesc, client);
2107 outputDesc->stop();
2108 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2109 config.channel_mask = info->getConfigBase().channel_mask;
2110 config.sample_rate = info->getConfigBase().sample_rate;
2111 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002112 sp<SwAudioOutputDescriptor> desc =
2113 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2114 if (desc == nullptr) {
2115 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002116 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002117 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002118 // Intentionally return error to let the client side resending request for
2119 // creating and starting.
2120 return DEAD_OBJECT;
2121 }
2122 info->increaseActiveClient();
2123 }
2124 }
2125
Eric Laurentc75307b2015-03-17 15:29:32 -07002126 if (delayMs != 0) {
2127 usleep(delayMs * 1000);
2128 }
2129
2130 return status;
2131}
2132
Eric Laurent96d1dda2022-03-14 17:14:19 +01002133bool AudioPolicyManager::isLeUnicastActive() const {
2134 if (isInCall()) {
2135 return true;
2136 }
2137 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2138}
2139
2140bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2141 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2142 return false;
2143 }
2144 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2145 ALOGV("%s active %d", __func__, active);
2146 return active;
2147}
2148
Eric Laurent97ac8712018-07-27 18:59:02 -07002149status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2150 const sp<TrackClientDescriptor>& client,
2151 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002152{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002153 // cannot start playback of STREAM_TTS if any other output is being used
2154 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002155
2156 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002157 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002158 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002159 auto clientStrategy = client->strategy();
2160 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002161 if (stream == AUDIO_STREAM_TTS) {
2162 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002163 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002164 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002165 return INVALID_OPERATION;
2166 } else {
2167 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2168 }
2169 } else {
2170 // some playback other than beacon starts
2171 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2172 }
2173
Eric Laurent77305a62016-07-25 16:39:22 -07002174 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002175 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002176 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002177
François Gaffie11d30102018-11-02 16:09:09 +01002178 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002179 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002180 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002181 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002182 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002183 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002184 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002185 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002186 } else {
2187 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002188 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002189 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2190 AUDIO_FORMAT_DEFAULT);
2191 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2192 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002193 }
2194
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002195 // requiresMuteCheck is false when we can bypass mute strategy.
2196 // It covers a common case when there is no materially active audio
2197 // and muting would result in unnecessary delay and dropped audio.
2198 const uint32_t outputLatencyMs = outputDesc->latency();
2199 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002200 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002201
Eric Laurente552edb2014-03-10 17:42:56 -07002202 // increment usage count for this stream on the requested output:
2203 // NOTE that the usage count is the same for duplicated output and hardware output which is
2204 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002205 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002206
2207 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002208 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2209 client->isPreferredDeviceForExclusiveUse()) {
2210 // Preferred device may be exclusive, use only if no other active clients on this output
2211 devices = DeviceVector(
2212 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2213 } else {
2214 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2215 }
François Gaffie11d30102018-11-02 16:09:09 +01002216 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002217 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002218 }
2219 }
Eric Laurente552edb2014-03-10 17:42:56 -07002220
François Gaffiec005e562018-11-06 15:04:49 +01002221 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002222 selectOutputForMusicEffects();
2223 }
2224
François Gaffie1c878552018-11-22 16:53:21 +01002225 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002226 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002227 if (devices.isEmpty()) {
2228 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002229 }
François Gaffiec005e562018-11-06 15:04:49 +01002230 bool shouldWait =
2231 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2232 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2233 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002234 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002235 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002236 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002237 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002238 // An output has a shared device if
2239 // - managed by the same hw module
2240 // - supports the currently selected device
2241 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002242 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002243
Eric Laurent77305a62016-07-25 16:39:22 -07002244 // force a device change if any other output is:
2245 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002246 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002247 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002248 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002249 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002250 // change the device currently selected by the other output.
2251 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002252 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002253 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002254 force = true;
2255 }
2256 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002257 // a notification so that audio focus effect can propagate, or that a mute/unmute
2258 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002259 const uint32_t latencyMs = desc->latency();
2260 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2261
2262 if (shouldWait && isActive && (waitMs < latencyMs)) {
2263 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002264 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002265
2266 // Require mute check if another output is on a shared device
2267 // and currently active to have proper drain and avoid pops.
2268 // Note restoring AudioTracks onto this output needs to invoke
2269 // a volume ramp if there is no mute.
2270 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002271 }
2272 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002273
jiabin3ff8d7d2022-12-13 06:27:44 +00002274 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2275 // If the output is open with preferred mixer attributes, but the routed device is
2276 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2277 // changed.
2278 return DEAD_OBJECT;
2279 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002280 const uint32_t muteWaitMs =
jiabin3ff8d7d2022-12-13 06:27:44 +00002281 setOutputDevices(outputDesc, devices, force, 0, nullptr, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002282
Eric Laurente552edb2014-03-10 17:42:56 -07002283 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002284 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002285 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002286 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002287 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002288 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002289 outputDesc->useHwGain() /*force*/)) {
2290 // request AudioService to reinitialize the volume curves asynchronously
2291 ALOGE("checkAndSetVolume failed, requesting volume range init");
2292 mpClientInterface->onVolumeRangeInitRequest();
2293 };
Eric Laurente552edb2014-03-10 17:42:56 -07002294
2295 // update the outputs if starting an output with a stream that can affect notification
2296 // routing
2297 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002298
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002299 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002300 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002301 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002302 }
Eric Laurentdc462862016-07-19 12:29:53 -07002303
2304 if (waitMs > muteWaitMs) {
2305 *delayMs = waitMs - muteWaitMs;
2306 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002307
2308 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2309 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2310 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2311 // change occurs after the MixerThread starts and causes a stream volume
2312 // glitch.
2313 //
2314 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002315 }
Eric Laurentdc462862016-07-19 12:29:53 -07002316
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002317 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002318 mEngine->getForceUse(
2319 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002320 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002321 }
2322
Eric Laurent97ac8712018-07-27 18:59:02 -07002323 // Automatically enable the remote submix input when output is started on a re routing mix
2324 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002325 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2326 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002327 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2328 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2329 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002330 "remote-submix",
2331 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002332 }
2333
Eric Laurent96d1dda2022-03-14 17:14:19 +01002334 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2335
Eric Laurente552edb2014-03-10 17:42:56 -07002336 return NO_ERROR;
2337}
2338
Eric Laurent96d1dda2022-03-14 17:14:19 +01002339void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2340 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2341 bool isUnicastActive = isLeUnicastActive();
2342
2343 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002344 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002345 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2346 for (size_t i = 0; i < mOutputs.size(); i++) {
2347 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2348 if (desc != ignoredOutput && desc->isActive()
2349 && ((isUnicastActive &&
2350 !desc->devices().
2351 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2352 || (wasUnicastActive &&
2353 !desc->devices().getDevicesFromTypes(
2354 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2355 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2356 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002357 if (desc->mUsePreferredMixerAttributes && force) {
2358 // If the device is using preferred mixer attributes, the output need to reopen
2359 // with default configuration when the new selected devices are different from
2360 // current routing devices.
2361 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2362 continue;
2363 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002364 setOutputDevices(desc, newDevices, force, delayMs);
2365 // re-apply device specific volume if not done by setOutputDevice()
2366 if (!force) {
2367 applyStreamVolumes(desc, newDevices.types(), delayMs);
2368 }
2369 }
2370 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002371 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002372 }
2373}
2374
Eric Laurent8fc147b2018-07-22 19:13:55 -07002375status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002376{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002377 ALOGV("%s portId %d", __FUNCTION__, portId);
2378
2379 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2380 if (outputDesc == 0) {
2381 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002382 return BAD_VALUE;
2383 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002384 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002385
Eric Laurent97ac8712018-07-27 18:59:02 -07002386 ALOGV("stopOutput() output %d, stream %d, session %d",
2387 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002388
Eric Laurent97ac8712018-07-27 18:59:02 -07002389 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002390
Eric Laurent733ce942017-12-07 12:18:25 -08002391 if (status == NO_ERROR ) {
2392 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002393 } else {
2394 return status;
2395 }
2396
2397 if (outputDesc->devices().size() == 1) {
2398 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2399 outputDesc->devices()[0]->getId(), client->strategy());
2400 if (info != nullptr && info->getUid() == client->uid()) {
2401 info->decreaseActiveClient();
2402 if (info->getActiveClientCount() == 0) {
2403 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2404 }
2405 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002406 }
2407 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002408}
2409
Eric Laurent97ac8712018-07-27 18:59:02 -07002410status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2411 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002412{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002413 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002414 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002415 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002416 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002417
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002418 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2419
François Gaffie1c878552018-11-22 16:53:21 +01002420 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2421 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002422 // Automatically disable the remote submix input when output is stopped on a
2423 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002424 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002425 if (isSingleDeviceType(
2426 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002427 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002428 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002429 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2430 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002431 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002432 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002433 }
2434 }
2435 bool forceDeviceUpdate = false;
2436 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002437 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002438 forceDeviceUpdate = true;
2439 }
2440
Eric Laurente552edb2014-03-10 17:42:56 -07002441 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002442 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002443
Eric Laurente552edb2014-03-10 17:42:56 -07002444 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002445 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002446 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002447 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002448
2449 // If the routing does not change, if an output is routed on a device using HwGain
2450 // (aka setAudioPortConfig) and there are still active clients following different
2451 // volume group(s), force reapply volume
2452 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2453 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2454
Eric Laurente552edb2014-03-10 17:42:56 -07002455 // delay the device switch by twice the latency because stopOutput() is executed when
2456 // the track stop() command is received and at that time the audio track buffer can
2457 // still contain data that needs to be drained. The latency only covers the audio HAL
2458 // and kernel buffers. Also the latency does not always include additional delay in the
2459 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002460 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2461 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002462
2463 // force restoring the device selection on other active outputs if it differs from the
2464 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002465 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002466 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002467 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002468 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002469 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002470 desc->isActive() &&
2471 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002472 (newDevices != desc->devices())) {
2473 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2474 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002475
jiabin3ff8d7d2022-12-13 06:27:44 +00002476 if (desc->mUsePreferredMixerAttributes && force) {
2477 // If the device is using preferred mixer attributes, the output need to
2478 // reopen with default configuration when the new selected devices are
2479 // different from current routing devices.
2480 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2481 continue;
2482 }
François Gaffie11d30102018-11-02 16:09:09 +01002483 setOutputDevices(desc, newDevices2, force, delayMs);
2484
Eric Laurent57de36c2016-09-28 16:59:11 -07002485 // re-apply device specific volume if not done by setOutputDevice()
2486 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002487 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002488 }
Eric Laurente552edb2014-03-10 17:42:56 -07002489 }
2490 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002491 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002492 // update the outputs if stopping one with a stream that can affect notification routing
2493 handleNotificationRoutingForStream(stream);
2494 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002495
2496 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2497 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002498 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002499 }
2500
François Gaffiec005e562018-11-06 15:04:49 +01002501 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002502 selectOutputForMusicEffects();
2503 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002504
2505 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2506
Eric Laurente552edb2014-03-10 17:42:56 -07002507 return NO_ERROR;
2508 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002509 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002510 return INVALID_OPERATION;
2511 }
2512}
2513
jiabinbce0c1d2020-10-05 11:20:18 -07002514bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002515{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002516 ALOGV("%s portId %d", __FUNCTION__, portId);
2517
2518 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2519 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002520 // If an output descriptor is closed due to a device routing change,
2521 // then there are race conditions with releaseOutput from tracks
2522 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2523 // destroyed shortly thereafter.
2524 //
2525 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002526 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002527 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002528 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002529
2530 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002531
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302532 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2533 if (outputDesc->isClientActive(client)) {
2534 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2535 stopOutput(portId);
2536 }
2537
Eric Laurent8fc147b2018-07-22 19:13:55 -07002538 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2539 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002540 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002541 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002542 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002543 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002544 if (--outputDesc->mDirectOpenCount == 0) {
2545 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002546 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002547 }
2548 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302549
Andy Hung39efb7a2018-09-26 15:39:28 -07002550 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002551 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2552 // The output is pending reopened to query dynamic profiles and
2553 // there is no active clients
2554 closeOutput(outputDesc->mIoHandle);
2555 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2556 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2557 if (newOutputDesc == nullptr) {
2558 ALOGE("%s failed to open output", __func__);
2559 }
2560 return true;
2561 }
2562 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002563}
2564
Eric Laurentcaf7f482014-11-25 17:50:47 -08002565status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2566 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002567 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002568 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002569 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002570 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002571 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002572 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002573 input_type_t *inputType,
2574 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002575{
François Gaffiec005e562018-11-06 15:04:49 +01002576 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002577 "flags %#x attributes=%s requested device ID %d",
2578 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2579 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002580
Eric Laurentad2e7b92017-09-14 20:06:42 -07002581 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002582 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002583 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002584 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002585 sp<AudioInputDescriptor> inputDesc;
2586 sp<RecordClientDescriptor> clientDesc;
2587 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002588 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002589 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002590
2591 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2592 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2593 return INVALID_OPERATION;
2594 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002595
Francois Gaffie716e1432019-01-14 16:58:59 +01002596 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2597 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002598 }
2599
Paul McLean466dc8e2015-04-17 13:15:36 -06002600 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002601 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002602 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002603
Eric Laurentad2e7b92017-09-14 20:06:42 -07002604 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2605 // possible
2606 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2607 *input != AUDIO_IO_HANDLE_NONE) {
2608 ssize_t index = mInputs.indexOfKey(*input);
2609 if (index < 0) {
2610 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2611 status = BAD_VALUE;
2612 goto error;
2613 }
2614 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002615 RecordClientVector clients = inputDesc->getClientsForSession(session);
2616 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002617 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2618 status = BAD_VALUE;
2619 goto error;
2620 }
2621 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2622 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002623 // corresponds to a new client and is only permitted from the same UID.
2624 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002625 if (clients.size() > 1) {
2626 for (const auto& client : clients) {
2627 // The client map is ordered by key values (portId) and portIds are allocated
2628 // incrementaly. So the first client in this list is the one opened by audio flinger
2629 // when the mmap stream is created and should be ignored as it does not correspond
2630 // to an actual client
2631 if (client == *clients.cbegin()) {
2632 continue;
2633 }
2634 if (uid != client->uid() && !client->isSilenced()) {
2635 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2636 uid, client->portId(), client->uid());
2637 status = INVALID_OPERATION;
2638 goto error;
2639 }
Eric Laurent331679c2018-04-16 17:03:16 -07002640 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002641 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002642 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002643 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002644
Eric Laurentfecbceb2021-02-09 14:46:43 +01002645 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002646 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002647 }
2648
2649 *input = AUDIO_IO_HANDLE_NONE;
2650 *inputType = API_INPUT_INVALID;
2651
Francois Gaffie716e1432019-01-14 16:58:59 +01002652 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002653 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002654 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002655 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002656 ALOGW("%s could not find input mix for attr %s",
2657 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002658 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002659 }
jiabinc1de2df2019-05-07 14:26:40 -07002660 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2661 String8(attr->tags + strlen("addr=")),
2662 AUDIO_FORMAT_DEFAULT);
2663 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002664 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002665 __func__, attributes.source, attributes.tags);
2666 status = BAD_VALUE;
2667 goto error;
2668 }
2669
Kevin Rocard25f9b052019-02-27 15:08:54 -08002670 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2671 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2672 } else {
2673 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2674 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002675 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002676 if (explicitRoutingDevice != nullptr) {
2677 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002678 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002679 // Prevent from storing invalid requested device id in clients
2680 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002681 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002682 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2683 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002684 }
François Gaffie11d30102018-11-02 16:09:09 +01002685 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002686 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002687 status = BAD_VALUE;
2688 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002689 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002690 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2691 *inputType = API_INPUT_MIX_CAPTURE;
2692 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002693 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2694 // there is an external policy, but this input is attached to a mix of recorders,
2695 // meaning it receives audio injected into the framework, so the recorder doesn't
2696 // know about it and is therefore considered "legacy"
2697 *inputType = API_INPUT_LEGACY;
2698 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002699 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002700 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002701 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002702 } else {
2703 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002704 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002705
Eric Laurent599c7582015-12-07 18:05:55 -08002706 }
2707
François Gaffiec005e562018-11-06 15:04:49 +01002708 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002709 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002710 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002711 AudioProfileVector profiles;
2712 status_t ret = getProfilesForDevices(
2713 DeviceVector(device), profiles, flags, true /*isInput*/);
2714 if (ret == NO_ERROR && !profiles.empty()) {
2715 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
2716 : *profiles[0]->getChannels().begin();
2717 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
2718 : *profiles[0]->getSampleRates().begin();
2719 config->format = profiles[0]->getFormat();
2720 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002721 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002722 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002723
Eric Laurent8f42ea12018-08-08 09:08:25 -07002724exit:
2725
François Gaffiec005e562018-11-06 15:04:49 +01002726 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2727 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002728
Francois Gaffie716e1432019-01-14 16:58:59 +01002729 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002730 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002731 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002732
Mikhail Naganov2996f672019-04-18 12:29:59 -07002733 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002734 requestedDeviceId, attributes.source, flags,
2735 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002736 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002737 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002738
2739 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2740 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002741
Eric Laurent599c7582015-12-07 18:05:55 -08002742 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002743
2744error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002745 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002746}
2747
2748
François Gaffie11d30102018-11-02 16:09:09 +01002749audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002750 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002751 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002752 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002753 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002754 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002755{
2756 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002757 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002758 bool isSoundTrigger = false;
2759
François Gaffiec005e562018-11-06 15:04:49 +01002760 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002761 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2762 if (index >= 0) {
2763 input = mSoundTriggerSessions.valueFor(session);
2764 isSoundTrigger = true;
2765 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2766 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2767 } else {
2768 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002769 }
François Gaffiec005e562018-11-06 15:04:49 +01002770 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002771 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002772 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002773 }
2774
Carter Hsua3abb402021-10-26 11:11:20 +08002775 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2776 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2777 }
2778
Eric Laurentfe231122017-11-17 17:48:06 -08002779 // sampling rate and flags may be updated by getInputProfile
2780 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2781 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002782 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002783 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002784 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002785 // find a compatible input profile (not necessarily identical in parameters)
2786 sp<IOProfile> profile = getInputProfile(
2787 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2788 if (profile == nullptr) {
2789 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002790 }
jiabin2fd710d2022-05-02 23:20:22 +00002791
Glenn Kasten05ddca52016-02-11 08:17:12 -08002792 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002793 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002794 if (samplingRate == 0) {
2795 samplingRate = profileSamplingRate;
2796 }
Eric Laurente552edb2014-03-10 17:42:56 -07002797
Eric Laurent322b4d22015-04-03 15:57:54 -07002798 if (profile->getModuleHandle() == 0) {
2799 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002800 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002801 }
2802
Eric Laurentec376dc2021-04-08 20:41:22 +02002803 // Reuse an already opened input if a client with the same session ID already exists
2804 // on that input
2805 for (size_t i = 0; i < mInputs.size(); i++) {
2806 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2807 if (desc->mProfile != profile) {
2808 continue;
2809 }
2810 RecordClientVector clients = desc->clientsList();
2811 for (const auto &client : clients) {
2812 if (session == client->session()) {
2813 return desc->mIoHandle;
2814 }
2815 }
2816 }
2817
Eric Laurent3974e3b2017-12-07 17:58:43 -08002818 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002819 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002820 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002821 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002822 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002823 continue;
2824 }
2825 // if sound trigger, reuse input if used by other sound trigger on same session
2826 // else
2827 // reuse input if active client app is not in IDLE state
2828 //
2829 RecordClientVector clients = desc->clientsList();
2830 bool doClose = false;
2831 for (const auto& client : clients) {
2832 if (isSoundTrigger != client->isSoundTrigger()) {
2833 continue;
2834 }
2835 if (client->isSoundTrigger()) {
2836 if (session == client->session()) {
2837 return desc->mIoHandle;
2838 }
2839 continue;
2840 }
2841 if (client->active() && client->appState() != APP_STATE_IDLE) {
2842 return desc->mIoHandle;
2843 }
2844 doClose = true;
2845 }
2846 if (doClose) {
2847 closeInput(desc->mIoHandle);
2848 } else {
2849 i++;
2850 }
2851 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002852 }
2853
Eric Laurentfe231122017-11-17 17:48:06 -08002854 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002855
Eric Laurentfe231122017-11-17 17:48:06 -08002856 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2857 lConfig.sample_rate = profileSamplingRate;
2858 lConfig.channel_mask = profileChannelMask;
2859 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002860
François Gaffie11d30102018-11-02 16:09:09 +01002861 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002862
2863 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002864 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002865 (profileSamplingRate != lConfig.sample_rate) ||
2866 !audio_formats_match(profileFormat, lConfig.format) ||
2867 (profileChannelMask != lConfig.channel_mask)) {
2868 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002869 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002870 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002871 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002872 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002873 }
Eric Laurent599c7582015-12-07 18:05:55 -08002874 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002875 }
2876
Eric Laurentc722f302014-12-10 11:21:49 -08002877 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002878
Eric Laurent599c7582015-12-07 18:05:55 -08002879 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002880 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002881
Eric Laurent599c7582015-12-07 18:05:55 -08002882 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002883}
2884
Eric Laurent4eb58f12018-12-07 16:41:02 -08002885status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002886{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002887 ALOGV("%s portId %d", __FUNCTION__, portId);
2888
2889 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2890 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002891 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002892 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002893 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002894 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002895 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002896 if (client->active()) {
2897 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2898 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002899 }
2900
Eric Laurent8f42ea12018-08-08 09:08:25 -07002901 audio_session_t session = client->session();
2902
Eric Laurent4eb58f12018-12-07 16:41:02 -08002903 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002904
Eric Laurent4eb58f12018-12-07 16:41:02 -08002905 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002906
Eric Laurent4eb58f12018-12-07 16:41:02 -08002907 status_t status = inputDesc->start();
2908 if (status != NO_ERROR) {
2909 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002910 }
Eric Laurente552edb2014-03-10 17:42:56 -07002911
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002912 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002913 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002914 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002915
Eric Laurent8f42ea12018-08-08 09:08:25 -07002916 // indicate active capture to sound trigger service if starting capture from a mic on
2917 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002918 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002919 if (device != nullptr) {
2920 status = setInputDevice(input, device, true /* force */);
2921 } else {
2922 ALOGW("%s no new input device can be found for descriptor %d",
2923 __FUNCTION__, inputDesc->getId());
2924 status = BAD_VALUE;
2925 }
Eric Laurente552edb2014-03-10 17:42:56 -07002926
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002927 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002928 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002929 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002930 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002931 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2932 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002933 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002934 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002935
François Gaffie11d30102018-11-02 16:09:09 +01002936 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2937 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002938 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002939 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002940 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002941
Eric Laurent8f42ea12018-08-08 09:08:25 -07002942 // automatically enable the remote submix output when input is started if not
2943 // used by a policy mix of type MIX_TYPE_RECORDERS
2944 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002945 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002946 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002947 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002948 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002949 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2950 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002951 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002952 if (address != "") {
2953 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2954 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002955 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002956 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002957 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002958 } else if (status != NO_ERROR) {
2959 // Restore client activity state.
2960 inputDesc->setClientActive(client, false);
2961 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002962 }
2963
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002964 ALOGV("%s input %d source = %d status = %d exit",
2965 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002966
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002967 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002968}
2969
Eric Laurent8fc147b2018-07-22 19:13:55 -07002970status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002971{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002972 ALOGV("%s portId %d", __FUNCTION__, portId);
2973
2974 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2975 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002976 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002977 return BAD_VALUE;
2978 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002979 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002980 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002981 if (!client->active()) {
2982 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002983 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002984 }
Carter Hsue6139d52021-07-08 10:30:20 +08002985 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002986 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002987
Eric Laurent8f42ea12018-08-08 09:08:25 -07002988 inputDesc->stop();
2989 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002990 auto current_source = inputDesc->source();
2991 setInputDevice(input, getNewInputDevice(inputDesc),
2992 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002993 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002994 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002995 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002996 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002997 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2998 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002999 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003000 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003001
3002 // automatically disable the remote submix output when input is stopped if not
3003 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003004 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003005 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003006 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003007 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003008 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3009 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003010 }
3011 if (address != "") {
3012 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3013 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003014 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003015 }
3016 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003017 resetInputDevice(input);
3018
3019 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3020 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003021 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3022 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003023 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003024 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003025 }
3026 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003027 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003028 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003029}
3030
Eric Laurent8fc147b2018-07-22 19:13:55 -07003031void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003032{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003033 ALOGV("%s portId %d", __FUNCTION__, portId);
3034
3035 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3036 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003037 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003038 return;
3039 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003040 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003041 audio_io_handle_t input = inputDesc->mIoHandle;
3042
Eric Laurent8f42ea12018-08-08 09:08:25 -07003043 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003044
Andy Hung39efb7a2018-09-26 15:39:28 -07003045 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08003046
Andy Hung39efb7a2018-09-26 15:39:28 -07003047 if (inputDesc->getClientCount() > 0) {
3048 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003049 return;
3050 }
3051
Eric Laurent05b90f82014-08-27 15:32:29 -07003052 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003053 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003054 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003055}
3056
Eric Laurent8f42ea12018-08-08 09:08:25 -07003057void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003058{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003059 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003060
3061 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003062 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003063 }
3064}
3065
Eric Laurent8f42ea12018-08-08 09:08:25 -07003066void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3067{
3068 stopInput(portId);
3069 releaseInput(portId);
3070}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003071
Eric Laurent0dd51852019-04-19 18:18:58 -07003072void AudioPolicyManager::checkCloseInputs() {
3073 // After connecting or disconnecting an input device, close input if:
3074 // - it has no client (was just opened to check profile) OR
3075 // - none of its supported devices are connected anymore OR
3076 // - one of its clients cannot be routed to one of its supported
3077 // devices anymore. Otherwise update device selection
3078 std::vector<audio_io_handle_t> inputsToClose;
3079 for (size_t i = 0; i < mInputs.size(); i++) {
3080 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3081 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003082 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003083 inputsToClose.push_back(mInputs.keyAt(i));
3084 } else {
3085 bool close = false;
3086 for (const auto& client : input->clientsList()) {
3087 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003088 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3089 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003090 if (!input->supportedDevices().contains(device)) {
3091 close = true;
3092 break;
3093 }
3094 }
3095 if (close) {
3096 inputsToClose.push_back(mInputs.keyAt(i));
3097 } else {
3098 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3099 }
3100 }
3101 }
3102
3103 for (const audio_io_handle_t handle : inputsToClose) {
3104 ALOGV("%s closing input %d", __func__, handle);
3105 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003106 }
Eric Laurentd4692962014-05-05 18:13:44 -07003107}
3108
François Gaffie251c7f02018-11-07 10:41:08 +01003109void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003110{
3111 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003112 if (indexMin < 0 || indexMax < 0) {
3113 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3114 return;
3115 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003116 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003117
3118 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003119 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3120 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003121 continue;
3122 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003123 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003124 }
Eric Laurente552edb2014-03-10 17:42:56 -07003125}
3126
Eric Laurente0720872014-03-11 09:30:41 -07003127status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003128 int index,
3129 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003130{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003131 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003132 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3133 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3134 return NO_ERROR;
3135 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003136 ALOGV("%s: stream %s attributes=%s", __func__,
3137 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003138 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003139}
3140
Eric Laurente0720872014-03-11 09:30:41 -07003141status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003142 int *index,
3143 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003144{
François Gaffiec005e562018-11-06 15:04:49 +01003145 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3146 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003147 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003148 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003149 deviceTypes = mEngine->getOutputDevicesForStream(
3150 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003151 }
jiabin9a3361e2019-10-01 09:38:30 -07003152 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003153}
3154
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003155status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003156 int index,
3157 audio_devices_t device)
3158{
3159 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003160 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3161 if (group == VOLUME_GROUP_NONE) {
3162 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003163 return BAD_VALUE;
3164 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003165 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003166 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003167 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003168 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003169 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3170 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3171 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3172 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003173 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3174
3175 status = setVolumeCurveIndex(index, device, curves);
3176 if (status != NO_ERROR) {
3177 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3178 return status;
3179 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003180
jiabin9a3361e2019-10-01 09:38:30 -07003181 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003182 auto curCurvAttrs = curves.getAttributes();
3183 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3184 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003185 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003186 } else if (!curves.getStreamTypes().empty()) {
3187 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003188 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003189 } else {
3190 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3191 return BAD_VALUE;
3192 }
jiabin9a3361e2019-10-01 09:38:30 -07003193 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3194 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003195
François Gaffiecfe17322018-11-07 13:41:29 +01003196 // update volume on all outputs and streams matching the following:
3197 // - The requested stream (or a stream matching for volume control) is active on the output
3198 // - The device (or devices) selected by the engine for this stream includes
3199 // the requested device
3200 // - For non default requested device, currently selected device on the output is either the
3201 // requested device or one of the devices selected by the engine for this stream
3202 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3203 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003204 for (size_t i = 0; i < mOutputs.size(); i++) {
3205 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003206 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003207
jiabin9a3361e2019-10-01 09:38:30 -07003208 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3209 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003210 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003211
3212 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003213 continue;
3214 }
3215 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3216 curDevices.find(device) == curDevices.end()) {
3217 continue;
3218 }
3219 bool applyVolume = false;
3220 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3221 curSrcDevices.insert(device);
3222 applyVolume = (curSrcDevices.find(
3223 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3224 } else {
3225 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3226 }
3227 if (!applyVolume) {
3228 continue; // next output
3229 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003230 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3231 // If a higher priority strategy is active, and the output is routed to a device with a
3232 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003233 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003234 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003235 // If the volume source is active with higher priority source, ensure at least Sw Muted
3236 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003237 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3238 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3239 false /*preferredDevice*/);
3240 if (activeClients.empty()) {
3241 continue;
3242 }
3243 bool isPreempted = false;
3244 bool isHigherPriority = productStrategy < strategy;
3245 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003246 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003247 ALOGV("%s: Strategy=%d (\nrequester:\n"
3248 " group %d, volumeGroup=%d attributes=%s)\n"
3249 " higher priority source active:\n"
3250 " volumeGroup=%d attributes=%s) \n"
3251 " on output %zu, bailing out", __func__, productStrategy,
3252 group, group, toString(attributes).c_str(),
3253 client->volumeSource(), toString(client->attributes()).c_str(), i);
3254 applyVolume = false;
3255 isPreempted = true;
3256 break;
3257 }
3258 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003259 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003260 applyVolume = true;
3261 }
3262 }
3263 if (isPreempted || applyVolume) {
3264 break;
3265 }
3266 }
3267 if (!applyVolume) {
3268 continue; // next output
3269 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003270 }
François Gaffieed91f582020-01-31 10:35:37 +01003271 //FIXME: workaround for truncated touch sounds
3272 // delayed volume change for system stream to be removed when the problem is
3273 // handled by system UI
3274 status_t volStatus = checkAndSetVolume(
3275 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003276 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003277 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3278 if (volStatus != NO_ERROR) {
3279 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003280 }
3281 }
François Gaffiecfe17322018-11-07 13:41:29 +01003282 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3283 return status;
3284}
3285
François Gaffieaaac0fd2018-11-22 17:56:39 +01003286status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003287 audio_devices_t device,
3288 IVolumeCurves &volumeCurves)
3289{
3290 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3291 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003292 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3293 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003294 (index > volumeCurves.getVolumeIndexMax())) {
3295 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3296 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3297 return BAD_VALUE;
3298 }
3299 if (!audio_is_output_device(device)) {
3300 return BAD_VALUE;
3301 }
3302
3303 // Force max volume if stream cannot be muted
3304 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3305
François Gaffieaaac0fd2018-11-22 17:56:39 +01003306 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003307 volumeCurves.addCurrentVolumeIndex(device, index);
3308 return NO_ERROR;
3309}
3310
3311status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3312 int &index,
3313 audio_devices_t device)
3314{
3315 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3316 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003317 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003318 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003319 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003320 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003321 }
jiabin9a3361e2019-10-01 09:38:30 -07003322 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003323}
3324
3325status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3326 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003327 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003328{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003329 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003330 return BAD_VALUE;
3331 }
jiabin9a3361e2019-10-01 09:38:30 -07003332 index = curves.getVolumeIndex(deviceTypes);
3333 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003334 return NO_ERROR;
3335}
3336
3337status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3338 int &index)
3339{
3340 index = getVolumeCurves(attr).getVolumeIndexMin();
3341 return NO_ERROR;
3342}
3343
3344status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3345 int &index)
3346{
3347 index = getVolumeCurves(attr).getVolumeIndexMax();
3348 return NO_ERROR;
3349}
3350
Eric Laurent36829f92017-04-07 19:04:42 -07003351audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003352{
3353 // select one output among several suitable for global effects.
3354 // The priority is as follows:
3355 // 1: An offloaded output. If the effect ends up not being offloadable,
3356 // AudioFlinger will invalidate the track and the offloaded output
3357 // will be closed causing the effect to be moved to a PCM output.
3358 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003359 // 3: The primary output
3360 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003361
François Gaffiec005e562018-11-06 15:04:49 +01003362 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3363 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003364 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003365
Eric Laurent36829f92017-04-07 19:04:42 -07003366 if (outputs.size() == 0) {
3367 return AUDIO_IO_HANDLE_NONE;
3368 }
Eric Laurente552edb2014-03-10 17:42:56 -07003369
Eric Laurent36829f92017-04-07 19:04:42 -07003370 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3371 bool activeOnly = true;
3372
3373 while (output == AUDIO_IO_HANDLE_NONE) {
3374 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3375 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3376 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3377
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003378 for (audio_io_handle_t output : outputs) {
3379 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003380 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003381 continue;
3382 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003383 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3384 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003385 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003386 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003387 }
3388 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003389 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003390 }
3391 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003392 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003393 }
3394 }
3395 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3396 output = outputOffloaded;
3397 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3398 output = outputDeepBuffer;
3399 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3400 output = outputPrimary;
3401 } else {
3402 output = outputs[0];
3403 }
3404 activeOnly = false;
3405 }
3406
3407 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003408 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003409 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3410 mMusicEffectOutput = output;
3411 }
3412
3413 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003414 return output;
3415}
3416
Eric Laurent36829f92017-04-07 19:04:42 -07003417audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3418{
3419 return selectOutputForMusicEffects();
3420}
3421
Eric Laurente0720872014-03-11 09:30:41 -07003422status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003423 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003424 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003425 int session,
3426 int id)
3427{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003428 if (session != AUDIO_SESSION_DEVICE) {
3429 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003430 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003431 index = mInputs.indexOfKey(io);
3432 if (index < 0) {
3433 ALOGW("registerEffect() unknown io %d", io);
3434 return INVALID_OPERATION;
3435 }
Eric Laurente552edb2014-03-10 17:42:56 -07003436 }
3437 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003438 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3439 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3440 || strategy == PRODUCT_STRATEGY_NONE));
3441 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003442}
3443
Eric Laurentc241b0d2018-11-28 09:08:49 -08003444status_t AudioPolicyManager::unregisterEffect(int id)
3445{
3446 if (mEffects.getEffect(id) == nullptr) {
3447 return INVALID_OPERATION;
3448 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003449 if (mEffects.isEffectEnabled(id)) {
3450 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3451 setEffectEnabled(id, false);
3452 }
3453 return mEffects.unregisterEffect(id);
3454}
3455
3456status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3457{
3458 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3459 if (effect == nullptr) {
3460 return INVALID_OPERATION;
3461 }
3462
3463 status_t status = mEffects.setEffectEnabled(id, enabled);
3464 if (status == NO_ERROR) {
3465 mInputs.trackEffectEnabled(effect, enabled);
3466 }
3467 return status;
3468}
3469
Eric Laurent6c796322019-04-09 14:13:17 -07003470
3471status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3472{
3473 mEffects.moveEffects(ids, io);
3474 return NO_ERROR;
3475}
3476
Eric Laurentc75307b2015-03-17 15:29:32 -07003477bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3478{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003479 auto vs = toVolumeSource(stream, false);
3480 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003481}
3482
3483bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3484{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003485 auto vs = toVolumeSource(stream, false);
3486 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003487}
3488
Eric Laurente0720872014-03-11 09:30:41 -07003489bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003490{
3491 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003492 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003493 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003494 return true;
3495 }
3496 }
3497 return false;
3498}
3499
Eric Laurent275e8e92014-11-30 15:14:47 -08003500// Register a list of custom mixes with their attributes and format.
3501// When a mix is registered, corresponding input and output profiles are
3502// added to the remote submix hw module. The profile contains only the
3503// parameters (sampling rate, format...) specified by the mix.
3504// The corresponding input remote submix device is also connected.
3505//
3506// When a remote submix device is connected, the address is checked to select the
3507// appropriate profile and the corresponding input or output stream is opened.
3508//
3509// When capture starts, getInputForAttr() will:
3510// - 1 look for a mix matching the address passed in attribtutes tags if any
3511// - 2 if none found, getDeviceForInputSource() will:
3512// - 2.1 look for a mix matching the attributes source
3513// - 2.2 if none found, default to device selection by policy rules
3514// At this time, the corresponding output remote submix device is also connected
3515// and active playback use cases can be transferred to this mix if needed when reconnecting
3516// after AudioTracks are invalidated
3517//
3518// When playback starts, getOutputForAttr() will:
3519// - 1 look for a mix matching the address passed in attribtutes tags if any
3520// - 2 if none found, look for a mix matching the attributes usage
3521// - 3 if none found, default to device and output selection by policy rules.
3522
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003523status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003524{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003525 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3526 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003527 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003528 sp<HwModule> rSubmixModule;
3529 // examine each mix's route type
3530 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003531 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003532 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3533 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3534 ALOGE("Unsupported Policy Mix %zu of %zu: "
3535 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3536 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003537 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003538 break;
3539 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003540 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3541 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003542 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003543 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3544 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003545 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003546 rSubmixModule = mHwModules.getModuleFromName(
3547 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3548 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003549 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003550 i);
3551 res = INVALID_OPERATION;
3552 break;
3553 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003554 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003555
Eric Laurent97ac8712018-07-27 18:59:02 -07003556 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003557 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003558 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003559 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003560 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3561 } else {
3562 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3563 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003564 }
François Gaffie036e1e92015-03-19 10:16:24 +01003565
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003566 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003567 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003568 res = INVALID_OPERATION;
3569 break;
3570 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003571 audio_config_t outputConfig = mix.mFormat;
3572 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003573 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3574 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003575 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3576 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003577 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003578 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003579 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003580 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003581
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003582 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003583 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3584 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3585 ALOGE("Failed to set remote submix device available, type %u, address %s",
3586 mix.mDeviceType, address.string());
3587 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003588 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003589 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3590 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003591 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003592 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003593 i, mixes.size(), type, address.string());
3594
3595 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3596 mix.mDeviceType, mix.mDeviceAddress,
3597 String8(), AUDIO_FORMAT_DEFAULT);
3598 if (device == nullptr) {
3599 res = INVALID_OPERATION;
3600 break;
3601 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003602
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003603 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003604 // First try to find an already opened output supporting the device
3605 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003606 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003607
Eric Laurentc529cf62020-04-17 18:19:10 -07003608 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003609 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003610 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3611 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003612 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003613 } else {
3614 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003615 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003616 }
3617 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003618 // If no output found, try to find a direct output profile supporting the device
3619 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3620 sp<HwModule> module = mHwModules[i];
3621 for (size_t j = 0;
3622 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3623 j++) {
3624 sp<IOProfile> profile = module->getOutputProfiles()[j];
3625 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3626 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3627 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3628 address.string());
3629 res = INVALID_OPERATION;
3630 } else {
3631 foundOutput = true;
3632 }
3633 }
3634 }
3635 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003636 if (res != NO_ERROR) {
3637 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003638 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003639 res = INVALID_OPERATION;
3640 break;
3641 } else if (!foundOutput) {
3642 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003643 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003644 res = INVALID_OPERATION;
3645 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003646 } else {
3647 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003648 }
Eric Laurentc722f302014-12-10 11:21:49 -08003649 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003650 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003651 if (res != NO_ERROR) {
3652 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003653 } else if (checkOutputs) {
3654 checkForDeviceAndOutputChanges();
3655 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003656 }
3657 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003658}
3659
3660status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3661{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003662 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003663 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003664 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003665 sp<HwModule> rSubmixModule;
3666 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003667 for (const auto& mix : mixes) {
3668 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003669
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003670 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003671 rSubmixModule = mHwModules.getModuleFromName(
3672 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3673 if (rSubmixModule == 0) {
3674 res = INVALID_OPERATION;
3675 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003676 }
3677 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003678
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003679 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003680
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003681 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003682 res = INVALID_OPERATION;
3683 continue;
3684 }
3685
Kevin Rocard04ed0462019-05-02 17:53:24 -07003686 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3687 if (getDeviceConnectionState(device, address.string()) ==
3688 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3689 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3690 address.string(), "remote-submix",
3691 AUDIO_FORMAT_DEFAULT);
3692 if (res != OK) {
3693 ALOGE("Error making RemoteSubmix device unavailable for mix "
3694 "with type %d, address %s", device, address.string());
3695 }
3696 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003697 }
jiabin5740f082019-08-19 15:08:30 -07003698 rSubmixModule->removeOutputProfile(address.c_str());
3699 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003700
Kevin Rocard153f92d2018-12-18 18:33:28 -08003701 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003702 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003703 res = INVALID_OPERATION;
3704 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003705 } else {
3706 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003707 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003708 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003709 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003710 if (res == NO_ERROR && checkOutputs) {
3711 checkForDeviceAndOutputChanges();
3712 updateCallAndOutputRouting();
3713 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003714 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003715}
3716
Mikhail Naganov100f0122018-11-29 11:22:16 -08003717void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3718{
3719 size_t i = 0;
3720 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3721 for (const auto& fmt : mManualSurroundFormats) {
3722 if (i++ != 0) dst->append(", ");
3723 std::string sfmt;
3724 FormatConverter::toString(fmt, sfmt);
3725 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3726 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3727 }
3728}
3729
Eric Laurentc529cf62020-04-17 18:19:10 -07003730// Returns true if all devices types match the predicate and are supported by one HW module
3731bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003732 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003733 std::function<bool(audio_devices_t)> predicate,
3734 const char *context) {
3735 for (size_t i = 0; i < devices.size(); i++) {
3736 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003737 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003738 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003739 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003740 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003741 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003742 return false;
3743 }
3744 }
3745 return true;
3746}
3747
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003748status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003749 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003750 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003751 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3752 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003753 }
3754 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003755 if (res != NO_ERROR) {
3756 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3757 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003758 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003759
3760 checkForDeviceAndOutputChanges();
3761 updateCallAndOutputRouting();
3762
3763 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003764}
3765
3766status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3767 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003768 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3769 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003770 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003771 __FUNCTION__, uid);
3772 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003773 }
3774
Eric Laurentc529cf62020-04-17 18:19:10 -07003775 checkForDeviceAndOutputChanges();
3776 updateCallAndOutputRouting();
3777
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003778 return res;
3779}
3780
Eric Laurent2517af32020-11-25 15:31:27 +01003781
jiabin0a488932020-08-07 17:32:40 -07003782status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3783 device_role_t role,
3784 const AudioDeviceTypeAddrVector &devices) {
3785 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3786 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003787
Eric Laurentc529cf62020-04-17 18:19:10 -07003788 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003789 return BAD_VALUE;
3790 }
jiabin0a488932020-08-07 17:32:40 -07003791 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003792 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003793 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3794 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003795 return status;
3796 }
3797
3798 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003799
3800 bool forceVolumeReeval = false;
3801 // FIXME: workaround for truncated touch sounds
3802 // to be removed when the problem is handled by system UI
3803 uint32_t delayMs = 0;
3804 if (strategy == mCommunnicationStrategy) {
3805 forceVolumeReeval = true;
3806 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3807 updateInputRouting();
3808 }
3809 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003810
3811 return NO_ERROR;
3812}
3813
3814void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3815{
3816 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003817 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003818 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003819 // Only apply special touch sound delay once
3820 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003821 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003822 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003823 for (size_t i = 0; i < mOutputs.size(); i++) {
3824 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3825 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003826 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3827 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003828 // As done in setDeviceConnectionState, we could also fix default device issue by
3829 // preventing the force re-routing in case of default dev that distinguishes on address.
3830 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003831 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003832 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3833 // If the device is using preferred mixer attributes, the output need to reopen
3834 // with default configuration when the new selected devices are different from
3835 // current routing devices.
3836 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3837 continue;
3838 }
Francois Gaffie601801d2021-06-22 13:27:39 +02003839 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3840 true /*requiresMuteCheck*/,
3841 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003842 // Only apply special touch sound delay once
3843 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003844 }
3845 if (forceVolumeReeval && !newDevices.isEmpty()) {
3846 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3847 }
3848 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003849 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01003850 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003851}
3852
Eric Laurent2517af32020-11-25 15:31:27 +01003853void AudioPolicyManager::updateInputRouting() {
3854 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303855 // Skip for hotword recording as the input device switch
3856 // is handled within sound trigger HAL
3857 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3858 continue;
3859 }
Eric Laurent2517af32020-11-25 15:31:27 +01003860 auto newDevice = getNewInputDevice(activeDesc);
3861 // Force new input selection if the new device can not be reached via current input
3862 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3863 setInputDevice(activeDesc->mIoHandle, newDevice);
3864 } else {
3865 closeInput(activeDesc->mIoHandle);
3866 }
3867 }
3868}
3869
jiabin0a488932020-08-07 17:32:40 -07003870status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3871 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003872{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003873 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003874
jiabin0a488932020-08-07 17:32:40 -07003875 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003876 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003877 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3878 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003879 return status;
3880 }
3881
3882 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003883
3884 bool forceVolumeReeval = false;
3885 // FIXME: workaround for truncated touch sounds
3886 // to be removed when the problem is handled by system UI
3887 uint32_t delayMs = 0;
3888 if (strategy == mCommunnicationStrategy) {
3889 forceVolumeReeval = true;
3890 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3891 updateInputRouting();
3892 }
3893 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003894
3895 return NO_ERROR;
3896}
3897
jiabin0a488932020-08-07 17:32:40 -07003898status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3899 device_role_t role,
3900 AudioDeviceTypeAddrVector &devices) {
3901 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003902}
3903
Jiabin Huang3b98d322020-09-03 17:54:16 +00003904status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3905 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3906 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3907 dumpAudioDeviceTypeAddrVector(devices).c_str());
3908
Mikhail Naganov55773032020-10-01 15:08:13 -07003909 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003910 return BAD_VALUE;
3911 }
3912 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3913 ALOGW_IF(status != NO_ERROR,
3914 "Engine could not set preferred devices %s for audio source %d role %d",
3915 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3916
3917 return status;
3918}
3919
3920status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3921 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3922 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3923 dumpAudioDeviceTypeAddrVector(devices).c_str());
3924
Mikhail Naganov55773032020-10-01 15:08:13 -07003925 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003926 return BAD_VALUE;
3927 }
3928 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3929 ALOGW_IF(status != NO_ERROR,
3930 "Engine could not add preferred devices %s for audio source %d role %d",
3931 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3932
Eric Laurent2517af32020-11-25 15:31:27 +01003933 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003934 return status;
3935}
3936
3937status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3938 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3939{
3940 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3941 dumpAudioDeviceTypeAddrVector(devices).c_str());
3942
Mikhail Naganov55773032020-10-01 15:08:13 -07003943 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003944 return BAD_VALUE;
3945 }
3946
3947 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3948 audioSource, role, devices);
3949 ALOGW_IF(status != NO_ERROR,
3950 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3951
Eric Laurent2517af32020-11-25 15:31:27 +01003952 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003953 return status;
3954}
3955
3956status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3957 device_role_t role) {
3958 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3959
3960 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3961 ALOGW_IF(status != NO_ERROR,
3962 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3963
Eric Laurent2517af32020-11-25 15:31:27 +01003964 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003965 return status;
3966}
3967
3968status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3969 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3970 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3971}
3972
Oscar Azucena90e77632019-11-27 17:12:28 -08003973status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003974 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003975 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003976 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3977 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003978 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003979 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3980 if (status != NO_ERROR) {
3981 ALOGE("%s() could not set device affinity for userId %d",
3982 __FUNCTION__, userId);
3983 return status;
3984 }
3985
3986 // reevaluate outputs for all devices
3987 checkForDeviceAndOutputChanges();
3988 updateCallAndOutputRouting();
3989
3990 return NO_ERROR;
3991}
3992
3993status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003994 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003995 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3996 if (status != NO_ERROR) {
3997 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3998 __FUNCTION__, userId);
3999 return status;
4000 }
4001
4002 // reevaluate outputs for all devices
4003 checkForDeviceAndOutputChanges();
4004 updateCallAndOutputRouting();
4005
4006 return NO_ERROR;
4007}
4008
Andy Hungc29d82b2018-10-05 12:23:17 -07004009void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004010{
Andy Hungc29d82b2018-10-05 12:23:17 -07004011 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004012 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004013 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004014 std::string stateLiteral;
4015 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004016 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004017 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4018 "communications", "media", "record", "dock", "system",
4019 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4020 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4021 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004022 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4023 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4024 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4025 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4026 dst->append(" (MANUAL: ");
4027 dumpManualSurroundFormats(dst);
4028 dst->append(")");
4029 }
4030 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004031 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004032 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4033 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004034 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07004035 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01004036
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004037 dst->append("\n");
4038 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4039 dst->append("\n");
4040 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004041 mHwModulesAll.dump(dst);
4042 mOutputs.dump(dst);
4043 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004044 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004045 mAudioPatches.dump(dst);
4046 mPolicyMixes.dump(dst);
4047 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004048
Kevin Rocardb99cc752019-03-21 20:52:24 -07004049 dst->appendFormat(" AllowedCapturePolicies:\n");
4050 for (auto& policy : mAllowedCapturePolicies) {
4051 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4052 }
4053
jiabina84c3d32022-12-02 18:59:55 +00004054 dst->appendFormat(" Preferred mixer audio configuration:\n");
4055 for (const auto it : mPreferredMixerAttrInfos) {
4056 dst->appendFormat(" - device port id: %d\n", it.first);
4057 for (const auto preferredMixerInfoIt : it.second) {
4058 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4059 preferredMixerInfoIt.second->dump(dst);
4060 }
4061 }
4062
François Gaffiec005e562018-11-06 15:04:49 +01004063 dst->appendFormat("\nPolicy Engine dump:\n");
4064 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004065}
4066
4067status_t AudioPolicyManager::dump(int fd)
4068{
4069 String8 result;
4070 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07004071 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004072 return NO_ERROR;
4073}
4074
Kevin Rocardb99cc752019-03-21 20:52:24 -07004075status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4076{
4077 mAllowedCapturePolicies[uid] = capturePolicy;
4078 return NO_ERROR;
4079}
4080
Eric Laurente552edb2014-03-10 17:42:56 -07004081// This function checks for the parameters which can be offloaded.
4082// This can be enhanced depending on the capability of the DSP and policy
4083// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004084audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004085{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004086 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004087 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004088 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004089 offloadInfo.format,
4090 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4091 offloadInfo.has_video);
4092
jiabin2b9d5a12021-12-10 01:06:29 +00004093 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004094 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004095 }
4096
4097 // See if there is a profile to support this.
4098 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004099 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004100 offloadInfo.sample_rate,
4101 offloadInfo.format,
4102 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004103 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4104 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004105 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4106 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4107 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004108 if (profile == nullptr) {
4109 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4110 }
4111 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4112 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4113 }
4114 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004115}
4116
Michael Chana94fbb22018-04-24 14:31:19 +10004117bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4118 const audio_attributes_t& attributes) {
4119 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004120 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004121 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4122 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004123 config.sample_rate,
4124 config.format,
4125 config.channel_mask,
4126 output_flags,
4127 true /* directOnly */);
4128 ALOGV("%s() profile %sfound with name: %s, "
4129 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4130 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004131 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004132 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004133
4134 // also try the MSD module if compatible profile not found
4135 if (profile == nullptr) {
4136 profile = getMsdProfileForOutput(outputDevices,
4137 config.sample_rate,
4138 config.format,
4139 config.channel_mask,
4140 output_flags,
4141 true /* directOnly */);
4142 ALOGV("%s() MSD profile %sfound with name: %s, "
4143 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4144 __FUNCTION__, profile != 0 ? "" : "NOT ",
4145 (profile != 0 ? profile->getTagName().c_str() : "null"),
4146 config.sample_rate, config.format, config.channel_mask, output_flags);
4147 }
4148 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004149}
4150
jiabin2b9d5a12021-12-10 01:06:29 +00004151bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4152 bool durationIgnored) {
4153 if (mMasterMono) {
4154 return false; // no offloading if mono is set.
4155 }
4156
4157 // Check if offload has been disabled
4158 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4159 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4160 return false;
4161 }
4162
4163 // Check if stream type is music, then only allow offload as of now.
4164 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4165 {
4166 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4167 return false;
4168 }
4169
4170 //TODO: enable audio offloading with video when ready
4171 const bool allowOffloadWithVideo =
4172 property_get_bool("audio.offload.video", false /* default_value */);
4173 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4174 ALOGV("%s: has_video == true, returning false", __func__);
4175 return false;
4176 }
4177
4178 //If duration is less than minimum value defined in property, return false
4179 const int min_duration_secs = property_get_int32(
4180 "audio.offload.min.duration.secs", -1 /* default_value */);
4181 if (!durationIgnored) {
4182 if (min_duration_secs >= 0) {
4183 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4184 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4185 __func__, min_duration_secs);
4186 return false;
4187 }
4188 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4189 ALOGV("%s: Offload denied by duration < default min(=%u)",
4190 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4191 return false;
4192 }
4193 }
4194
4195 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4196 // creating an offloaded track and tearing it down immediately after start when audioflinger
4197 // detects there is an active non offloadable effect.
4198 // FIXME: We should check the audio session here but we do not have it in this context.
4199 // This may prevent offloading in rare situations where effects are left active by apps
4200 // in the background.
4201 if (mEffects.isNonOffloadableEffectEnabled()) {
4202 return false;
4203 }
4204
4205 return true;
4206}
4207
4208audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4209 const audio_config_t *config) {
4210 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4211 offloadInfo.format = config->format;
4212 offloadInfo.sample_rate = config->sample_rate;
4213 offloadInfo.channel_mask = config->channel_mask;
4214 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4215 offloadInfo.has_video = false;
4216 offloadInfo.is_streaming = false;
4217 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4218
4219 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4220 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4221 audio_flags_to_audio_output_flags(attr->flags, &flags);
4222 // only retain flags that will drive compressed offload or passthrough
4223 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4224 if (offloadPossible) {
4225 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4226 }
4227 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4228
Dorin Drimusfae3c642022-03-17 18:36:30 +01004229 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004230 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004231 DeviceVector outputDevices = engineOutputDevices;
4232 // the MSD module checks for different conditions and output devices
4233 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4234 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4235 continue;
4236 }
4237 outputDevices = getMsdAudioOutDevices();
4238 }
jiabin2b9d5a12021-12-10 01:06:29 +00004239 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004240 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004241 config->sample_rate, nullptr /*updatedSamplingRate*/,
4242 config->format, nullptr /*updatedFormat*/,
4243 config->channel_mask, nullptr /*updatedChannelMask*/,
4244 flags)) {
4245 continue;
4246 }
4247 // reject profiles not corresponding to a device currently available
4248 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4249 continue;
4250 }
4251 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4252 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004253 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004254 != AUDIO_DIRECT_NOT_SUPPORTED) {
4255 // Already reports offload gapless supported. No need to report offload support.
4256 continue;
4257 }
4258 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4259 != AUDIO_OUTPUT_FLAG_NONE) {
4260 // If offload gapless is reported, no need to report offload support.
4261 directMode = (audio_direct_mode_t) ((directMode &
4262 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4263 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4264 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004265 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004266 }
4267 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004268 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004269 }
4270 }
4271 }
4272 return directMode;
4273}
4274
Dorin Drimusf2196d82022-01-03 12:11:18 +01004275status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4276 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004277 if (mEffects.isNonOffloadableEffectEnabled()) {
4278 return OK;
4279 }
jiabinf1c73972022-04-14 16:28:52 -07004280 DeviceVector devices;
4281 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004282 if (status != OK) {
4283 return status;
4284 }
4285 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4286 if (devices.empty()) {
4287 return OK; // no output devices for the attributes
4288 }
jiabinf1c73972022-04-14 16:28:52 -07004289 return getProfilesForDevices(devices, audioProfilesVector,
4290 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004291}
4292
jiabina84c3d32022-12-02 18:59:55 +00004293status_t AudioPolicyManager::getSupportedMixerAttributes(
4294 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4295 ALOGV("%s, portId=%d", __func__, portId);
4296 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4297 if (deviceDescriptor == nullptr) {
4298 ALOGE("%s the requested device is currently unavailable", __func__);
4299 return BAD_VALUE;
4300 }
4301 for (const auto& hwModule : mHwModules) {
4302 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4303 if (curProfile->supportsDevice(deviceDescriptor)) {
4304 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4305 }
4306 }
4307 }
4308 return NO_ERROR;
4309}
4310
4311status_t AudioPolicyManager::setPreferredMixerAttributes(
4312 const audio_attributes_t *attr,
4313 audio_port_handle_t portId,
4314 uid_t uid,
4315 const audio_mixer_attributes_t *mixerAttributes) {
4316 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4317 "mixerBehavior=%d}, uid=%d, portId=%u",
4318 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4319 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4320 mixerAttributes->mixer_behavior, uid, portId);
4321 if (attr->usage != AUDIO_USAGE_MEDIA) {
4322 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4323 return BAD_VALUE;
4324 }
4325 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4326 if (deviceDescriptor == nullptr) {
4327 ALOGE("%s the requested device is currently unavailable", __func__);
4328 return BAD_VALUE;
4329 }
4330 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4331 ALOGE("%s(%d), type=%d, is not a usb output device",
4332 __func__, portId, deviceDescriptor->type());
4333 return BAD_VALUE;
4334 }
4335
4336 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4337 audio_flags_to_audio_output_flags(attr->flags, &flags);
4338 flags = (audio_output_flags_t) (flags |
4339 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4340 sp<IOProfile> profile = nullptr;
4341 DeviceVector devices(deviceDescriptor);
4342 for (const auto& hwModule : mHwModules) {
4343 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4344 if (curProfile->hasDynamicAudioProfile()
4345 && curProfile->isCompatibleProfile(devices,
4346 mixerAttributes->config.sample_rate,
4347 nullptr /*updatedSamplingRate*/,
4348 mixerAttributes->config.format,
4349 nullptr /*updatedFormat*/,
4350 mixerAttributes->config.channel_mask,
4351 nullptr /*updatedChannelMask*/,
4352 flags,
4353 false /*exactMatchRequiredForInputFlags*/)) {
4354 profile = curProfile;
4355 break;
4356 }
4357 }
4358 }
4359 if (profile == nullptr) {
4360 ALOGE("%s, there is no compatible profile found", __func__);
4361 return BAD_VALUE;
4362 }
4363
4364 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4365 sp<PreferredMixerAttributesInfo>::make(
4366 uid, portId, profile, flags, *mixerAttributes);
4367 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4368 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4369
4370 // If 1) there is any client from the preferred mixer configuration owner that is currently
4371 // active and matches the strategy and 2) current output is on the preferred device and the
4372 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4373 // configuration.
4374 std::vector<audio_io_handle_t> outputsToReopen;
4375 for (size_t i = 0; i < mOutputs.size(); i++) {
4376 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004377 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4378 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4379 output->mUsePreferredMixerAttributes = true;
4380 } else {
4381 for (const auto &client: output->getActiveClients()) {
4382 if (client->uid() == uid && client->strategy() == strategy) {
4383 client->setIsInvalid();
4384 outputsToReopen.push_back(output->mIoHandle);
4385 }
jiabina84c3d32022-12-02 18:59:55 +00004386 }
4387 }
4388 }
4389 }
4390 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4391 config.sample_rate = mixerAttributes->config.sample_rate;
4392 config.channel_mask = mixerAttributes->config.channel_mask;
4393 config.format = mixerAttributes->config.format;
4394 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004395 sp<SwAudioOutputDescriptor> desc =
4396 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4397 if (desc == nullptr) {
4398 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4399 continue;
4400 }
4401 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004402 }
4403
4404 return NO_ERROR;
4405}
4406
4407sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
4408 audio_port_handle_t devicePortId, product_strategy_t strategy) {
4409 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4410 if (it == mPreferredMixerAttrInfos.end()) {
4411 return nullptr;
4412 }
4413 auto mixerAttrInfoIt = it->second.find(strategy);
4414 if (mixerAttrInfoIt == it->second.end()) {
4415 return nullptr;
4416 }
4417 return mixerAttrInfoIt->second;
4418}
4419
4420status_t AudioPolicyManager::getPreferredMixerAttributes(
4421 const audio_attributes_t *attr,
4422 audio_port_handle_t portId,
4423 audio_mixer_attributes_t* mixerAttributes) {
4424 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4425 portId, mEngine->getProductStrategyForAttributes(*attr));
4426 if (info == nullptr) {
4427 return NAME_NOT_FOUND;
4428 }
4429 *mixerAttributes = info->getMixerAttributes();
4430 return NO_ERROR;
4431}
4432
4433status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4434 audio_port_handle_t portId,
4435 uid_t uid) {
4436 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4437 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4438 if (preferredMixerAttrInfo == nullptr) {
4439 return NAME_NOT_FOUND;
4440 }
4441 if (preferredMixerAttrInfo->getUid() != uid) {
4442 ALOGE("%s, requested uid=%d, owned uid=%d",
4443 __func__, uid, preferredMixerAttrInfo->getUid());
4444 return PERMISSION_DENIED;
4445 }
4446 mPreferredMixerAttrInfos[portId].erase(strategy);
4447 if (mPreferredMixerAttrInfos[portId].empty()) {
4448 mPreferredMixerAttrInfos.erase(portId);
4449 }
4450
4451 // Reconfig existing output
4452 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4453 for (size_t i = 0; i < mOutputs.size(); i++) {
4454 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4455 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4456 }
4457 }
4458 for (const auto output : potentialOutputsToReopen) {
4459 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4460 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4461 preferredMixerAttrInfo->getFlags())) {
4462 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4463 }
4464 }
4465 return NO_ERROR;
4466}
4467
Eric Laurent6a94d692014-05-20 11:18:06 -07004468status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4469 audio_port_type_t type,
4470 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004471 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004472 unsigned int *generation)
4473{
jiabin19cdba52020-11-24 11:28:58 -08004474 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4475 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004476 return BAD_VALUE;
4477 }
4478 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004479 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004480 *num_ports = 0;
4481 }
4482
4483 size_t portsWritten = 0;
4484 size_t portsMax = *num_ports;
4485 *num_ports = 0;
4486 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004487 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4488 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004489 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004490 for (const auto& dev : mAvailableOutputDevices) {
4491 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004492 continue;
4493 }
4494 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004495 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004496 }
4497 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004498 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004499 }
4500 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004501 for (const auto& dev : mAvailableInputDevices) {
4502 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004503 continue;
4504 }
4505 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004506 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004507 }
4508 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004509 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004510 }
4511 }
4512 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4513 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4514 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4515 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4516 }
4517 *num_ports += mInputs.size();
4518 }
4519 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004520 size_t numOutputs = 0;
4521 for (size_t i = 0; i < mOutputs.size(); i++) {
4522 if (!mOutputs[i]->isDuplicated()) {
4523 numOutputs++;
4524 if (portsWritten < portsMax) {
4525 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4526 }
4527 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004528 }
Eric Laurent84c70242014-06-23 08:46:27 -07004529 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004530 }
4531 }
jiabina84c3d32022-12-02 18:59:55 +00004532
Eric Laurent6a94d692014-05-20 11:18:06 -07004533 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004534 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004535 return NO_ERROR;
4536}
4537
jiabin19cdba52020-11-24 11:28:58 -08004538status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004539{
Eric Laurent99fcae42018-05-17 16:59:18 -07004540 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4541 return BAD_VALUE;
4542 }
4543 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4544 if (dev != 0) {
4545 dev->toAudioPort(port);
4546 return NO_ERROR;
4547 }
4548 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4549 if (dev != 0) {
4550 dev->toAudioPort(port);
4551 return NO_ERROR;
4552 }
4553 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4554 if (out != 0) {
4555 out->toAudioPort(port);
4556 return NO_ERROR;
4557 }
4558 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4559 if (in != 0) {
4560 in->toAudioPort(port);
4561 return NO_ERROR;
4562 }
4563 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004564}
4565
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004566status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4567 audio_patch_handle_t *handle,
4568 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004569{
François Gaffieafd4cea2019-11-18 15:50:22 +01004570 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004571 if (handle == NULL || patch == NULL) {
4572 return BAD_VALUE;
4573 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004574 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004575 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004576 return BAD_VALUE;
4577 }
4578 // only one source per audio patch supported for now
4579 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004580 return INVALID_OPERATION;
4581 }
Eric Laurent874c42872014-08-08 15:13:39 -07004582 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004583 return INVALID_OPERATION;
4584 }
Eric Laurent874c42872014-08-08 15:13:39 -07004585 for (size_t i = 0; i < patch->num_sinks; i++) {
4586 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4587 return INVALID_OPERATION;
4588 }
4589 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004590
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004591 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4592 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4593 if (srcDevice == nullptr || sinkDevice == nullptr) {
4594 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4595 return BAD_VALUE;
4596 }
4597 ALOGV("%s between source %s and sink %s", __func__,
4598 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4599 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4600 // Default attributes, default volume priority, not to infer with non raw audio patches.
4601 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4602 const struct audio_port_config *source = &patch->sources[0];
4603 sp<SourceClientDescriptor> sourceDesc =
4604 new InternalSourceClientDescriptor(
4605 portId, uid, attributes, *source, srcDevice, sinkDevice,
4606 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4607
4608 status_t status =
4609 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4610
4611 if (status != NO_ERROR) {
4612 return INVALID_OPERATION;
4613 }
4614 mAudioSources.add(portId, sourceDesc);
4615 return NO_ERROR;
4616}
4617
4618status_t AudioPolicyManager::connectAudioSourceToSink(
4619 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4620 const struct audio_patch *patch,
4621 audio_patch_handle_t &handle,
4622 uid_t uid, uint32_t delayMs)
4623{
4624 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4625 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4626 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4627 return INVALID_OPERATION;
4628 }
4629 sourceDesc->connect(handle, sinkDevice);
4630 if (isMsdPatch(handle)) {
4631 return NO_ERROR;
4632 }
4633 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4634 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4635 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4636 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4637 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4638 goto FailurePatchAdded;
4639 }
4640 status = swOutput->start();
4641 if (status != NO_ERROR) {
4642 goto FailureSourceAdded;
4643 }
4644 swOutput->addClient(sourceDesc);
4645 status = startSource(swOutput, sourceDesc, &delayMs);
4646 if (status != NO_ERROR) {
4647 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4648 goto FailureSourceActive;
4649 }
4650 if (delayMs != 0) {
4651 usleep(delayMs * 1000);
4652 }
4653 return NO_ERROR;
4654
4655FailureSourceActive:
4656 swOutput->stop();
4657 releaseOutput(sourceDesc->portId());
4658FailureSourceAdded:
4659 sourceDesc->setSwOutput(nullptr);
4660FailurePatchAdded:
4661 releaseAudioPatchInternal(handle);
4662 return INVALID_OPERATION;
4663}
4664
4665status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4666 audio_patch_handle_t *handle,
4667 uid_t uid, uint32_t delayMs,
4668 const sp<SourceClientDescriptor>& sourceDesc)
4669{
4670 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004671 sp<AudioPatch> patchDesc;
4672 ssize_t index = mAudioPatches.indexOfKey(*handle);
4673
François Gaffieafd4cea2019-11-18 15:50:22 +01004674 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4675 patch->sources[0].role,
4676 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004677#if LOG_NDEBUG == 0
4678 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004679 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4680 patch->sinks[i].role,
4681 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004682 }
4683#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004684
4685 if (index >= 0) {
4686 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004687 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4688 __func__, mUidCached, patchDesc->getUid(), uid);
4689 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004690 return INVALID_OPERATION;
4691 }
4692 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004693 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004694 }
4695
4696 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004697 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004698 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004699 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004700 return BAD_VALUE;
4701 }
Eric Laurent84c70242014-06-23 08:46:27 -07004702 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4703 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004704 if (patchDesc != 0) {
4705 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004706 ALOGV("%s source id differs for patch current id %d new id %d",
4707 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004708 return BAD_VALUE;
4709 }
4710 }
Eric Laurent874c42872014-08-08 15:13:39 -07004711 DeviceVector devices;
4712 for (size_t i = 0; i < patch->num_sinks; i++) {
4713 // Only support mix to devices connection
4714 // TODO add support for mix to mix connection
4715 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004716 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004717 return INVALID_OPERATION;
4718 }
4719 sp<DeviceDescriptor> devDesc =
4720 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4721 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004722 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004723 return BAD_VALUE;
4724 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004725
François Gaffie11d30102018-11-02 16:09:09 +01004726 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004727 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004728 NULL, // updatedSamplingRate
4729 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004730 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004731 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004732 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004733 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004734 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004735 return INVALID_OPERATION;
4736 }
4737 devices.add(devDesc);
4738 }
4739 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004740 return INVALID_OPERATION;
4741 }
Eric Laurent874c42872014-08-08 15:13:39 -07004742
Eric Laurent6a94d692014-05-20 11:18:06 -07004743 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004744 ALOGV("%s setting device %s on output %d",
4745 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004746 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004747 index = mAudioPatches.indexOfKey(*handle);
4748 if (index >= 0) {
4749 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004750 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004751 }
4752 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004753 patchDesc->setUid(uid);
4754 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004755 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004756 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004757 return INVALID_OPERATION;
4758 }
4759 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4760 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4761 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004762 // only one sink supported when connecting an input device to a mix
4763 if (patch->num_sinks > 1) {
4764 return INVALID_OPERATION;
4765 }
François Gaffie53615e22015-03-19 09:24:12 +01004766 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004767 if (inputDesc == NULL) {
4768 return BAD_VALUE;
4769 }
4770 if (patchDesc != 0) {
4771 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4772 return BAD_VALUE;
4773 }
4774 }
François Gaffie11d30102018-11-02 16:09:09 +01004775 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004776 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004777 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004778 return BAD_VALUE;
4779 }
4780
François Gaffie11d30102018-11-02 16:09:09 +01004781 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004782 patch->sinks[0].sample_rate,
4783 NULL, /*updatedSampleRate*/
4784 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004785 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004786 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004787 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004788 // FIXME for the parameter type,
4789 // and the NONE
4790 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004791 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004792 return INVALID_OPERATION;
4793 }
4794 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004795 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004796 device->toString().c_str(), inputDesc->mIoHandle);
4797 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004798 index = mAudioPatches.indexOfKey(*handle);
4799 if (index >= 0) {
4800 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004801 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004802 }
4803 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004804 patchDesc->setUid(uid);
4805 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004806 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004807 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004808 return INVALID_OPERATION;
4809 }
4810 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4811 // device to device connection
4812 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004813 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004814 return BAD_VALUE;
4815 }
4816 }
François Gaffie11d30102018-11-02 16:09:09 +01004817 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004818 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004819 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004820 return BAD_VALUE;
4821 }
Eric Laurent874c42872014-08-08 15:13:39 -07004822
Eric Laurent6a94d692014-05-20 11:18:06 -07004823 //update source and sink with our own data as the data passed in the patch may
4824 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004825 PatchBuilder patchBuilder;
4826 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004827
4828 // if first sink is to MSD, establish single MSD patch
4829 if (getMsdAudioOutDevices().contains(
4830 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4831 ALOGV("%s patching to MSD", __FUNCTION__);
4832 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4833 goto installPatch;
4834 }
4835
François Gaffieafd4cea2019-11-18 15:50:22 +01004836 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4837 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004838
Eric Laurent874c42872014-08-08 15:13:39 -07004839 for (size_t i = 0; i < patch->num_sinks; i++) {
4840 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004841 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004842 return INVALID_OPERATION;
4843 }
François Gaffie11d30102018-11-02 16:09:09 +01004844 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004845 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004846 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004847 return BAD_VALUE;
4848 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004849 audio_port_config sinkPortConfig = {};
4850 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4851 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004852
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004853 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4854 // volume management purpose (tracking activity)
4855 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4856 // in config XML to reach the sink so that is can be declared as available.
4857 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004858 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004859 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004860 // take care of dynamic routing for SwOutput selection,
4861 audio_attributes_t attributes = sourceDesc->attributes();
4862 audio_stream_type_t stream = sourceDesc->stream();
4863 audio_attributes_t resultAttr;
4864 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4865 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02004866 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
4867 config.channel_mask =
4868 (audio_channel_mask_get_representation(sourceMask)
4869 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
4870 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004871 config.format = sourceDesc->config().format;
4872 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4873 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4874 bool isRequestedDeviceForExclusiveUse = false;
4875 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004876 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00004877 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004878 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4879 &stream, sourceDesc->uid(), &config, &flags,
4880 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00004881 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004882 if (output == AUDIO_IO_HANDLE_NONE) {
4883 ALOGV("%s no output for device %s",
4884 __FUNCTION__, sinkDevice->toString().c_str());
4885 return INVALID_OPERATION;
4886 }
4887 outputDesc = mOutputs.valueFor(output);
4888 if (outputDesc->isDuplicated()) {
4889 ALOGE("%s output is duplicated", __func__);
4890 return INVALID_OPERATION;
4891 }
François Gaffie7e39df22022-04-26 12:48:49 +02004892 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4893 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004894 } else {
4895 // Same for "raw patches" aka created from createAudioPatch API
4896 SortedVector<audio_io_handle_t> outputs =
4897 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4898 // if the sink device is reachable via an opened output stream, request to
4899 // go via this output stream by adding a second source to the patch
4900 // description
4901 output = selectOutput(outputs);
4902 if (output == AUDIO_IO_HANDLE_NONE) {
4903 ALOGE("%s no output available for internal patch sink", __func__);
4904 return INVALID_OPERATION;
4905 }
4906 outputDesc = mOutputs.valueFor(output);
4907 if (outputDesc->isDuplicated()) {
4908 ALOGV("%s output for device %s is duplicated",
4909 __func__, sinkDevice->toString().c_str());
4910 return INVALID_OPERATION;
4911 }
François Gaffie7e39df22022-04-26 12:48:49 +02004912 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004913 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004914 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004915 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004916 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004917 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004918 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4919 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004920 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4921 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004922 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004923 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004924 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004925 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004926 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004927 return INVALID_OPERATION;
4928 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004929 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004930 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004931 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004932 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004933 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02004934 srcMixPortConfig.ext.mix.usecase.stream =
4935 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004936 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4937 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004938 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004939 }
Eric Laurent83b88082014-06-20 18:31:16 -07004940 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004941 }
4942 // TODO: check from routing capabilities in config file and other conflicting patches
4943
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004944installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004945 status_t status = installPatch(
4946 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004947 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004948 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004949 return INVALID_OPERATION;
4950 }
4951 } else {
4952 return BAD_VALUE;
4953 }
4954 } else {
4955 return BAD_VALUE;
4956 }
4957 return NO_ERROR;
4958}
4959
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004960status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004961{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004962 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004963 ssize_t index = mAudioPatches.indexOfKey(handle);
4964
4965 if (index < 0) {
4966 return BAD_VALUE;
4967 }
4968 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004969 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4970 __func__, mUidCached, patchDesc->getUid(), uid);
4971 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004972 return INVALID_OPERATION;
4973 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004974 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4975 for (size_t i = 0; i < mAudioSources.size(); i++) {
4976 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4977 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4978 portId = sourceDesc->portId();
4979 break;
4980 }
4981 }
4982 return portId != AUDIO_PORT_HANDLE_NONE ?
4983 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004984}
Eric Laurent6a94d692014-05-20 11:18:06 -07004985
François Gaffieafd4cea2019-11-18 15:50:22 +01004986status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004987 uint32_t delayMs,
4988 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004989{
4990 ALOGV("%s patch %d", __func__, handle);
4991 if (mAudioPatches.indexOfKey(handle) < 0) {
4992 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4993 return BAD_VALUE;
4994 }
4995 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004996 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004997 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004998 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004999 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005000 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005001 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005002 return BAD_VALUE;
5003 }
5004
François Gaffie11d30102018-11-02 16:09:09 +01005005 setOutputDevices(outputDesc,
5006 getNewOutputDevices(outputDesc, true /*fromCache*/),
5007 true,
5008 0,
5009 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005010 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5011 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005012 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005013 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005014 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005015 return BAD_VALUE;
5016 }
5017 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005018 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005019 true,
5020 NULL);
5021 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005022 status_t status =
5023 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5024 ALOGV("%s patch panel returned %d patchHandle %d",
5025 __func__, status, patchDesc->getAfHandle());
5026 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005027 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005028 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005029 // SW or HW Bridge
5030 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5031 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005032 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005033 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5034 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5035 outputDesc = sourceDesc->swOutput().promote();
5036 }
5037 if (outputDesc == nullptr) {
5038 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5039 // releaseOutput has already called closeOutput in case of direct output
5040 return NO_ERROR;
5041 }
François Gaffie7e39df22022-04-26 12:48:49 +02005042 patchHandle = outputDesc->getPatchHandle();
5043 // When a Sw bridge is released, the mixer used by this bridge will release its
5044 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
5045 // Reuse patch handle to force audio flinger removing initial mixer patch removal
5046 // updating hal patch handle (prevent leaks).
5047 // While using a HwBridge, force reconsidering device only if not reusing an existing
5048 // output and no more activity on output (will force to close).
5049 bool force = sourceDesc->useSwBridge() ||
5050 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
5051 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5052 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5053 // Reconsider device only for cases:
5054 // 1 / Active Output
5055 // 2 / Inactive Output previously hosting HwBridge
5056 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5057 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5058 sourceDesc->canCloseOutput();
5059 setOutputDevices(outputDesc,
5060 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5061 outputDesc->devices(),
5062 force,
5063 0,
5064 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005065 } else {
5066 return BAD_VALUE;
5067 }
5068 } else {
5069 return BAD_VALUE;
5070 }
5071 return NO_ERROR;
5072}
5073
5074status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5075 struct audio_patch *patches,
5076 unsigned int *generation)
5077{
François Gaffie53615e22015-03-19 09:24:12 +01005078 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005079 return BAD_VALUE;
5080 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005081 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005082 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005083}
5084
Eric Laurente1715a42014-05-20 11:30:42 -07005085status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005086{
Eric Laurente1715a42014-05-20 11:30:42 -07005087 ALOGV("setAudioPortConfig()");
5088
5089 if (config == NULL) {
5090 return BAD_VALUE;
5091 }
5092 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5093 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005094 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5095 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005096 }
5097
Eric Laurenta121f902014-06-03 13:32:54 -07005098 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005099 if (config->type == AUDIO_PORT_TYPE_MIX) {
5100 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005101 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005102 if (outputDesc == NULL) {
5103 return BAD_VALUE;
5104 }
Eric Laurent84c70242014-06-23 08:46:27 -07005105 ALOG_ASSERT(!outputDesc->isDuplicated(),
5106 "setAudioPortConfig() called on duplicated output %d",
5107 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005108 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005109 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005110 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005111 if (inputDesc == NULL) {
5112 return BAD_VALUE;
5113 }
Eric Laurenta121f902014-06-03 13:32:54 -07005114 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005115 } else {
5116 return BAD_VALUE;
5117 }
5118 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5119 sp<DeviceDescriptor> deviceDesc;
5120 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5121 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5122 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5123 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5124 } else {
5125 return BAD_VALUE;
5126 }
5127 if (deviceDesc == NULL) {
5128 return BAD_VALUE;
5129 }
Eric Laurenta121f902014-06-03 13:32:54 -07005130 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005131 } else {
5132 return BAD_VALUE;
5133 }
5134
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005135 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005136 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5137 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005138 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005139 audioPortConfig->toAudioPortConfig(&newConfig, config);
5140 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005141 }
Eric Laurenta121f902014-06-03 13:32:54 -07005142 if (status != NO_ERROR) {
5143 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005144 }
Eric Laurente1715a42014-05-20 11:30:42 -07005145
5146 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005147}
5148
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005149void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5150{
Eric Laurentd60560a2015-04-10 11:31:20 -07005151 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005152 clearAudioPatches(uid);
5153 clearSessionRoutes(uid);
5154}
5155
Eric Laurent6a94d692014-05-20 11:18:06 -07005156void AudioPolicyManager::clearAudioPatches(uid_t uid)
5157{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005158 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005159 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005160 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005161 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005162 }
5163 }
5164}
5165
François Gaffiec005e562018-11-06 15:04:49 +01005166void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005167{
François Gaffiec005e562018-11-06 15:04:49 +01005168 // Take the first attributes following the product strategy as it is used to retrieve the routed
5169 // device. All attributes wihin a strategy follows the same "routing strategy"
5170 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5171 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005172 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005173 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005174 for (size_t j = 0; j < mOutputs.size(); j++) {
5175 if (mOutputs.keyAt(j) == ouptutToSkip) {
5176 continue;
5177 }
5178 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005179 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005180 continue;
5181 }
5182 // If the default device for this strategy is on another output mix,
5183 // invalidate all tracks in this strategy to force re connection.
5184 // Otherwise select new device on the output mix.
5185 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005186 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005187 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005188 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5189 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5190 // If the device is using preferred mixer attributes, the output need to reopen
5191 // with default configuration when the new selected devices are different from
5192 // current routing devices.
5193 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5194 continue;
5195 }
5196 setOutputDevices(outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005197 }
5198 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005199 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005200}
5201
5202void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5203{
5204 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005205 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005206 for (size_t i = 0; i < mOutputs.size(); i++) {
5207 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005208 for (const auto& client : outputDesc->getClientIterable()) {
5209 if (client->hasPreferredDevice() && client->uid() == uid) {
5210 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005211 auto clientStrategy = client->strategy();
5212 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5213 end(affectedStrategies)) {
5214 continue;
5215 }
5216 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005217 }
5218 }
5219 }
5220 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005221 for (const auto& strategy : affectedStrategies) {
5222 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005223 }
5224
5225 // remove input routes associated with this uid
5226 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005227 for (size_t i = 0; i < mInputs.size(); i++) {
5228 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005229 for (const auto& client : inputDesc->getClientIterable()) {
5230 if (client->hasPreferredDevice() && client->uid() == uid) {
5231 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5232 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005233 }
5234 }
5235 }
5236 // reroute inputs if necessary
5237 SortedVector<audio_io_handle_t> inputsToClose;
5238 for (size_t i = 0; i < mInputs.size(); i++) {
5239 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005240 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005241 inputsToClose.add(inputDesc->mIoHandle);
5242 }
5243 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005244 for (const auto& input : inputsToClose) {
5245 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005246 }
5247}
5248
Eric Laurentd60560a2015-04-10 11:31:20 -07005249void AudioPolicyManager::clearAudioSources(uid_t uid)
5250{
5251 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005252 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5253 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005254 stopAudioSource(mAudioSources.keyAt(i));
5255 }
5256 }
5257}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005258
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005259status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5260 audio_io_handle_t *ioHandle,
5261 audio_devices_t *device)
5262{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005263 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5264 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005265 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01005266 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005267
François Gaffiedf372692015-03-19 10:43:27 +01005268 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005269}
5270
Eric Laurentd60560a2015-04-10 11:31:20 -07005271status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005272 const audio_attributes_t *attributes,
5273 audio_port_handle_t *portId,
5274 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005275{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005276 ALOGV("%s", __FUNCTION__);
5277 *portId = AUDIO_PORT_HANDLE_NONE;
5278
5279 if (source == NULL || attributes == NULL || portId == NULL) {
5280 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5281 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005282 return BAD_VALUE;
5283 }
5284
Eric Laurentd60560a2015-04-10 11:31:20 -07005285 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5286 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005287 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5288 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005289 return INVALID_OPERATION;
5290 }
5291
François Gaffie11d30102018-11-02 16:09:09 +01005292 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005293 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005294 String8(source->ext.device.address),
5295 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005296 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005297 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005298 return BAD_VALUE;
5299 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005300
jiabin4ef93452019-09-10 14:29:54 -07005301 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005302
François Gaffieaaac0fd2018-11-22 17:56:39 +01005303 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005304 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005305 mEngine->getStreamTypeForAttributes(*attributes),
5306 mEngine->getProductStrategyForAttributes(*attributes),
5307 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005308
5309 status_t status = connectAudioSource(sourceDesc);
5310 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005311 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005312 }
5313 return status;
5314}
5315
Francois Gaffie601801d2021-06-22 13:27:39 +02005316sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5317 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5318{
5319 ALOGV("%s", __FUNCTION__);
5320 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5321
5322 status_t status = startAudioSource(source, attributes, &portId, uid);
5323 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5324 return mAudioSources.valueFor(portId);
5325}
5326
5327
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005328status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005329{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005330 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005331
5332 // make sure we only have one patch per source.
5333 disconnectAudioSource(sourceDesc);
5334
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005335 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005336 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5337 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5338 sourceDesc->srcDevice()->type(),
5339 String8(sourceDesc->srcDevice()->address().c_str()),
5340 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005341 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005342 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005343 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005344 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005345 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5346 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5347 return INVALID_OPERATION;
5348 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005349 PatchBuilder patchBuilder;
5350 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5351 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005352
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005353 return connectAudioSourceToSink(
5354 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005355}
5356
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005357status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005358{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005359 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5360 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005361 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005362 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005363 return BAD_VALUE;
5364 }
5365 status_t status = disconnectAudioSource(sourceDesc);
5366
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005367 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005368 return status;
5369}
5370
Andy Hung2ddee192015-12-18 17:34:44 -08005371status_t AudioPolicyManager::setMasterMono(bool mono)
5372{
5373 if (mMasterMono == mono) {
5374 return NO_ERROR;
5375 }
5376 mMasterMono = mono;
5377 // if enabling mono we close all offloaded devices, which will invalidate the
5378 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5379 // for recreating the new AudioTrack as non-offloaded PCM.
5380 //
5381 // If disabling mono, we leave all tracks as is: we don't know which clients
5382 // and tracks are able to be recreated as offloaded. The next "song" should
5383 // play back offloaded.
5384 if (mMasterMono) {
5385 Vector<audio_io_handle_t> offloaded;
5386 for (size_t i = 0; i < mOutputs.size(); ++i) {
5387 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5388 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5389 offloaded.push(desc->mIoHandle);
5390 }
5391 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005392 for (const auto& handle : offloaded) {
5393 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005394 }
5395 }
5396 // update master mono for all remaining outputs
5397 for (size_t i = 0; i < mOutputs.size(); ++i) {
5398 updateMono(mOutputs.keyAt(i));
5399 }
5400 return NO_ERROR;
5401}
5402
5403status_t AudioPolicyManager::getMasterMono(bool *mono)
5404{
5405 *mono = mMasterMono;
5406 return NO_ERROR;
5407}
5408
Eric Laurentac9cef52017-06-09 15:46:26 -07005409float AudioPolicyManager::getStreamVolumeDB(
5410 audio_stream_type_t stream, int index, audio_devices_t device)
5411{
jiabin9a3361e2019-10-01 09:38:30 -07005412 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005413}
5414
jiabin81772902018-04-02 17:52:27 -07005415status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5416 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005417 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005418{
Kriti Dang6537def2021-03-02 13:46:59 +01005419 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5420 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005421 return BAD_VALUE;
5422 }
Kriti Dang6537def2021-03-02 13:46:59 +01005423 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5424 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005425
5426 size_t formatsWritten = 0;
5427 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005428
Kriti Dang6537def2021-03-02 13:46:59 +01005429 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005430 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5431 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005432 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005433 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005434 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005435 bool formatEnabled = true;
5436 switch (forceUse) {
5437 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005438 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005439 break;
5440 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5441 formatEnabled = false;
5442 break;
5443 default: // AUTO or ALWAYS => true
5444 break;
jiabin81772902018-04-02 17:52:27 -07005445 }
5446 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5447 }
jiabin81772902018-04-02 17:52:27 -07005448 }
5449 return NO_ERROR;
5450}
5451
Kriti Dang6537def2021-03-02 13:46:59 +01005452status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5453 audio_format_t *surroundFormats) {
5454 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5455 return BAD_VALUE;
5456 }
5457 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5458 __func__, *numSurroundFormats, surroundFormats);
5459
5460 size_t formatsWritten = 0;
5461 size_t formatsMax = *numSurroundFormats;
5462 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5463
5464 // Return formats from all device profiles that have already been resolved by
5465 // checkOutputsForDevice().
5466 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5467 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5468 audio_devices_t deviceType = device->type();
5469 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5470 // returns formats reported by HDMI devices.
5471 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5472 continue;
5473 }
5474 // Formats reported by sink devices
5475 std::unordered_set<audio_format_t> formatset;
5476 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5477 formatset.insert(it->second.begin(), it->second.end());
5478 }
5479
5480 // Formats hard-coded in the in policy configuration file (if any).
5481 FormatVector encodedFormats = device->encodedFormats();
5482 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5483 // Filter the formats which are supported by the vendor hardware.
5484 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5485 if (mConfig.getSurroundFormats().count(*it) != 0) {
5486 formats.insert(*it);
5487 } else {
5488 for (const auto& pair : mConfig.getSurroundFormats()) {
5489 if (pair.second.count(*it) != 0) {
5490 formats.insert(pair.first);
5491 break;
5492 }
5493 }
5494 }
5495 }
5496 }
5497 *numSurroundFormats = formats.size();
5498 for (const auto& format: formats) {
5499 if (formatsWritten < formatsMax) {
5500 surroundFormats[formatsWritten++] = format;
5501 }
5502 }
5503 return NO_ERROR;
5504}
5505
jiabin81772902018-04-02 17:52:27 -07005506status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5507{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005508 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005509 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5510 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005511 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005512 return BAD_VALUE;
5513 }
5514
Mikhail Naganov100f0122018-11-29 11:22:16 -08005515 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5516 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005517 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005518 return INVALID_OPERATION;
5519 }
5520
Mikhail Naganov100f0122018-11-29 11:22:16 -08005521 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005522 return NO_ERROR;
5523 }
5524
Mikhail Naganov100f0122018-11-29 11:22:16 -08005525 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005526 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005527 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005528 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005529 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005530 }
5531 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005532 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005533 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005534 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005535 }
5536 }
5537
5538 sp<SwAudioOutputDescriptor> outputDesc;
5539 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005540 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5541 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005542 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5543 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005544 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005545 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005546 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5547 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5548 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005549 name.c_str(),
5550 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005551 if (status != NO_ERROR) {
5552 continue;
5553 }
5554 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5555 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5556 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005557 name.c_str(),
5558 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005559 profileUpdated |= (status == NO_ERROR);
5560 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005561 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005562 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005563 AUDIO_DEVICE_IN_HDMI);
5564 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5565 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005566 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005567 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005568 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5569 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5570 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005571 name.c_str(),
5572 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005573 if (status != NO_ERROR) {
5574 continue;
5575 }
5576 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5577 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5578 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005579 name.c_str(),
5580 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005581 profileUpdated |= (status == NO_ERROR);
5582 }
5583
jiabin81772902018-04-02 17:52:27 -07005584 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005585 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005586 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005587 }
5588
5589 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5590}
5591
Eric Laurent5ada82e2019-08-29 17:53:54 -07005592void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005593{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005594 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005595 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005596 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005597 }
5598}
5599
jiabin6012f912018-11-02 17:06:30 -07005600bool AudioPolicyManager::isHapticPlaybackSupported()
5601{
5602 for (const auto& hwModule : mHwModules) {
5603 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5604 for (const auto &outProfile : outputProfiles) {
5605 struct audio_port audioPort;
5606 outProfile->toAudioPort(&audioPort);
5607 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5608 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5609 return true;
5610 }
5611 }
5612 }
5613 }
5614 return false;
5615}
5616
Carter Hsu325a8eb2022-01-19 19:56:51 +08005617bool AudioPolicyManager::isUltrasoundSupported()
5618{
5619 bool hasUltrasoundOutput = false;
5620 bool hasUltrasoundInput = false;
5621 for (const auto& hwModule : mHwModules) {
5622 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5623 if (!hasUltrasoundOutput) {
5624 for (const auto &outProfile : outputProfiles) {
5625 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5626 hasUltrasoundOutput = true;
5627 break;
5628 }
5629 }
5630 }
5631
5632 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5633 if (!hasUltrasoundInput) {
5634 for (const auto &inputProfile : inputProfiles) {
5635 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5636 hasUltrasoundInput = true;
5637 break;
5638 }
5639 }
5640 }
5641
5642 if (hasUltrasoundOutput && hasUltrasoundInput)
5643 return true;
5644 }
5645 return false;
5646}
5647
Atneya Nair698f5ef2022-12-15 16:15:09 -08005648bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5649{
5650 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5651 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5652 for (const auto& hwModule : mHwModules) {
5653 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5654 for (const auto &inputProfile : inputProfiles) {
5655 if ((inputProfile->getFlags() & mask) == mask) {
5656 return true;
5657 }
5658 }
5659 }
5660 return false;
5661}
5662
Eric Laurent8340e672019-11-06 11:01:08 -08005663bool AudioPolicyManager::isCallScreenModeSupported()
5664{
5665 return getConfig().isCallScreenModeSupported();
5666}
5667
5668
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005669status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005670{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005671 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005672 if (!sourceDesc->isConnected()) {
5673 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5674 return NO_ERROR;
5675 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005676 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5677 if (swOutput != 0) {
5678 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005679 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005680 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005681 }
jiabinbce0c1d2020-10-05 11:20:18 -07005682 if (releaseOutput(sourceDesc->portId())) {
5683 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5684 // no need to release audio patch here but just return NO_ERROR.
5685 return NO_ERROR;
5686 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005687 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005688 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005689 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005690 // close Hwoutput and remove from mHwOutputs
5691 } else {
5692 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5693 }
5694 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005695 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005696 sourceDesc->disconnect();
5697 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005698}
5699
François Gaffiec005e562018-11-06 15:04:49 +01005700sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5701 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005702{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005703 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005704 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005705 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005706 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005707 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5708 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005709 source = sourceDesc;
5710 break;
5711 }
5712 }
5713 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005714}
5715
Eric Laurentb4f42a92022-01-17 17:37:31 +01005716bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005717 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005718 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005719{
5720 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5721 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005722 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005723 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005724 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5725 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5726 return false;
5727 }
5728 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5729 return false;
5730 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005731 }
5732
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005733 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005734 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005735 if (profile == nullptr) {
5736 return false;
5737 }
5738
5739 // The caller can have the audio config criteria ignored by either passing a null ptr or
5740 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005741 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005742 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005743
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005744 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005745 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005746 return false;
5747 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005748 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005749 return true;
5750}
5751
5752void AudioPolicyManager::checkVirtualizerClientRoutes() {
5753 std::set<audio_stream_type_t> streamsToInvalidate;
5754 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005755 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5756 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005757 audio_attributes_t attr = client->attributes();
5758 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5759 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5760 audio_config_base_t clientConfig = client->config();
5761 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005762 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005763 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005764 streamsToInvalidate.insert(client->stream());
5765 }
5766 }
5767 }
5768
jiabinc44b3462022-12-08 12:52:31 -08005769 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005770}
5771
Eric Laurente191d1b2022-04-15 11:59:25 +02005772
5773bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5774 const sp<SwAudioOutputDescriptor>& outputDesc) {
5775 if (outputDesc->isDuplicated()) {
5776 return false;
5777 }
5778 DeviceVector devices = outputDesc->supportedDevices();
5779 for (size_t i = 0; i < mOutputs.size(); i++) {
5780 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5781 if (desc == outputDesc || desc->isDuplicated()) {
5782 continue;
5783 }
5784 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5785 if (!sharedDevices.isEmpty()
5786 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5787 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5788 return false;
5789 }
5790 }
5791 return true;
5792}
5793
5794
Eric Laurentfa0f6742021-08-17 18:39:44 +02005795status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005796 const audio_attributes_t *attr,
5797 audio_io_handle_t *output) {
5798 *output = AUDIO_IO_HANDLE_NONE;
5799
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005800 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5801 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5802 audio_config_t *configPtr = nullptr;
5803 audio_config_t config;
5804 if (mixerConfig != nullptr) {
5805 config = audio_config_initializer(mixerConfig);
5806 configPtr = &config;
5807 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005808 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005809 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005810 return BAD_VALUE;
5811 }
5812
5813 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005814 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005815 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005816 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005817 return BAD_VALUE;
5818 }
5819
Eric Laurente191d1b2022-04-15 11:59:25 +02005820 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005821 for (size_t i = 0; i < mOutputs.size(); i++) {
5822 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005823 if (!desc->isDuplicated()
5824 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5825 spatializerOutputs.push_back(desc);
5826 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005827 }
5828 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005829 mSpatializerOutput.clear();
5830 bool outputsChanged = false;
5831 for (const auto& desc : spatializerOutputs) {
5832 if (desc->mProfile == profile
5833 && (configPtr == nullptr
5834 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5835 mSpatializerOutput = desc;
5836 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5837 } else {
5838 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5839 " and devices %s", __func__, desc->mIoHandle,
5840 configPtr != nullptr ? configPtr->channel_mask : 0,
5841 devices.toString().c_str());
5842 closeOutput(desc->mIoHandle);
5843 outputsChanged = true;
5844 }
Eric Laurent39095982021-08-24 18:29:27 +02005845 }
5846
Eric Laurente191d1b2022-04-15 11:59:25 +02005847 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005848 sp<SwAudioOutputDescriptor> desc =
5849 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005850 if (desc != nullptr) {
5851 mSpatializerOutput = desc;
5852 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005853 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005854 }
5855
5856 checkVirtualizerClientRoutes();
5857
Eric Laurente191d1b2022-04-15 11:59:25 +02005858 if (outputsChanged) {
5859 mPreviousOutputs = mOutputs;
5860 mpClientInterface->onAudioPortListUpdate();
5861 }
5862
5863 if (mSpatializerOutput == nullptr) {
5864 ALOGV("%s could not open spatializer output with requested config", __func__);
5865 return BAD_VALUE;
5866 }
Eric Laurent39095982021-08-24 18:29:27 +02005867 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005868 ALOGV("%s returning new spatializer output %d", __func__, *output);
5869 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005870}
5871
Eric Laurentfa0f6742021-08-17 18:39:44 +02005872status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5873 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005874 return INVALID_OPERATION;
5875 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005876 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005877 return BAD_VALUE;
5878 }
Eric Laurent39095982021-08-24 18:29:27 +02005879
Eric Laurente191d1b2022-04-15 11:59:25 +02005880 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5881 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5882 closeOutput(mSpatializerOutput->mIoHandle);
5883 //from now on mSpatializerOutput is null
5884 checkVirtualizerClientRoutes();
5885 }
Eric Laurent39095982021-08-24 18:29:27 +02005886
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005887 return NO_ERROR;
5888}
5889
Eric Laurente552edb2014-03-10 17:42:56 -07005890// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005891// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005892// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005893uint32_t AudioPolicyManager::nextAudioPortGeneration()
5894{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005895 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005896}
5897
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005898static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005899 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5900 !audioPolicyXmlConfigFile.empty()) {
5901 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5902 if (ret == NO_ERROR) {
5903 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005904 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005905 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005906 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005907 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005908}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005909
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005910AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5911 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005912 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005913 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005914 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005915 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005916 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005917 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005918 mAudioPortGeneration(1),
5919 mBeaconMuteRefCount(0),
5920 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005921 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005922 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005923 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005924 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005925{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005926}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005927
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005928AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5929 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5930{
5931 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005932}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005933
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005934void AudioPolicyManager::loadConfig() {
5935 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005936 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005937 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005938 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005939}
5940
5941status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005942 {
5943 auto engLib = EngineLibrary::load(
5944 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5945 if (!engLib) {
5946 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5947 return NO_INIT;
5948 }
5949 mEngine = engLib->createEngine();
5950 if (mEngine == nullptr) {
5951 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5952 return NO_INIT;
5953 }
François Gaffie2110e042015-03-24 08:41:51 +01005954 }
5955 mEngine->setObserver(this);
5956 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005957 if (status != NO_ERROR) {
5958 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5959 return status;
5960 }
François Gaffie2110e042015-03-24 08:41:51 +01005961
Eric Laurent1a8b45f2022-04-13 16:01:47 +02005962 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005963 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5964 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5965
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005966 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005967 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005968 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005969
Eric Laurent3a4311c2014-03-17 12:00:47 -07005970 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005971 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5972 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5973 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005974 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005975 }
jiabin9ff780e2018-03-19 18:19:52 -07005976 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005977 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005978 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005979 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005980 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005981 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005982 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005983 }
5984 }
5985 }
Eric Laurente552edb2014-03-10 17:42:56 -07005986
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005987 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005988
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005989 // Silence ALOGV statements
5990 property_set("log.tag." LOG_TAG, "D");
5991
Eric Laurente552edb2014-03-10 17:42:56 -07005992 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005993 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005994}
5995
Eric Laurente0720872014-03-11 09:30:41 -07005996AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005997{
Eric Laurente552edb2014-03-10 17:42:56 -07005998 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005999 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006000 }
6001 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006002 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006003 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006004 mAvailableOutputDevices.clear();
6005 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006006 mOutputs.clear();
6007 mInputs.clear();
6008 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08006009 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006010 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006011}
6012
Eric Laurente0720872014-03-11 09:30:41 -07006013status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006014{
Eric Laurent87ffa392015-05-22 10:32:38 -07006015 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006016}
6017
Eric Laurente552edb2014-03-10 17:42:56 -07006018// ---
6019
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006020void AudioPolicyManager::onNewAudioModulesAvailable()
6021{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006022 DeviceVector newDevices;
6023 onNewAudioModulesAvailableInt(&newDevices);
6024 if (!newDevices.empty()) {
6025 nextAudioPortGeneration();
6026 mpClientInterface->onAudioPortListUpdate();
6027 }
6028}
6029
6030void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6031{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006032 for (const auto& hwModule : mHwModulesAll) {
6033 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6034 continue;
6035 }
6036 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
6037 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
6038 ALOGW("could not open HW module %s", hwModule->getName());
6039 continue;
6040 }
6041 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006042 // open all output streams needed to access attached devices.
6043 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006044 // This also validates mAvailableOutputDevices list
6045 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6046 if (!outProfile->canOpenNewIo()) {
6047 ALOGE("Invalid Output profile max open count %u for profile %s",
6048 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6049 continue;
6050 }
6051 if (!outProfile->hasSupportedDevices()) {
6052 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6053 continue;
6054 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006055 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6056 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006057 mTtsOutputAvailable = true;
6058 }
6059
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006060 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
6061 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
6062 sp<DeviceDescriptor> supportedDevice = 0;
6063 if (supportedDevices.contains(mDefaultOutputDevice)) {
6064 supportedDevice = mDefaultOutputDevice;
6065 } else {
6066 // choose first device present in profile's SupportedDevices also part of
6067 // mAvailableOutputDevices.
6068 if (availProfileDevices.isEmpty()) {
6069 continue;
6070 }
6071 supportedDevice = availProfileDevices.itemAt(0);
6072 }
6073 if (!mOutputDevicesAll.contains(supportedDevice)) {
6074 continue;
6075 }
6076 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6077 mpClientInterface);
6078 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006079 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6080 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006081 AUDIO_STREAM_DEFAULT,
6082 AUDIO_OUTPUT_FLAG_NONE, &output);
6083 if (status != NO_ERROR) {
6084 ALOGW("Cannot open output stream for devices %s on hw module %s",
6085 supportedDevice->toString().c_str(), hwModule->getName());
6086 continue;
6087 }
6088 for (const auto &device : availProfileDevices) {
6089 // give a valid ID to an attached device once confirmed it is reachable
6090 if (!device->isAttached()) {
6091 device->attach(hwModule);
6092 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006093 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006094 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006095 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6096 }
6097 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006098 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006099 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6100 mPrimaryOutput = outputDesc;
6101 }
Eric Laurent39095982021-08-24 18:29:27 +02006102 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006103 outputDesc->close();
6104 } else {
6105 addOutput(output, outputDesc);
6106 setOutputDevices(outputDesc,
6107 DeviceVector(supportedDevice),
6108 true,
6109 0,
6110 NULL);
6111 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006112 }
6113 // open input streams needed to access attached devices to validate
6114 // mAvailableInputDevices list
6115 for (const auto& inProfile : hwModule->getInputProfiles()) {
6116 if (!inProfile->canOpenNewIo()) {
6117 ALOGE("Invalid Input profile max open count %u for profile %s",
6118 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6119 continue;
6120 }
6121 if (!inProfile->hasSupportedDevices()) {
6122 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6123 continue;
6124 }
6125 // chose first device present in profile's SupportedDevices also part of
6126 // available input devices
6127 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
6128 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
6129 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006130 ALOGV("%s: Input device list is empty! for profile %s",
6131 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006132 continue;
6133 }
6134 sp<AudioInputDescriptor> inputDesc =
6135 new AudioInputDescriptor(inProfile, mpClientInterface);
6136
6137 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6138 status_t status = inputDesc->open(nullptr,
6139 availProfileDevices.itemAt(0),
6140 AUDIO_SOURCE_MIC,
6141 AUDIO_INPUT_FLAG_NONE,
6142 &input);
6143 if (status != NO_ERROR) {
6144 ALOGW("Cannot open input stream for device %s on hw module %s",
6145 availProfileDevices.toString().c_str(),
6146 hwModule->getName());
6147 continue;
6148 }
6149 for (const auto &device : availProfileDevices) {
6150 // give a valid ID to an attached device once confirmed it is reachable
6151 if (!device->isAttached()) {
6152 device->attach(hwModule);
6153 device->importAudioPortAndPickAudioProfile(inProfile, true);
6154 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006155 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006156 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6157 }
6158 }
6159 inputDesc->close();
6160 }
6161 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006162
6163 // Check if spatializer outputs can be closed until used.
6164 // mOutputs vector never contains duplicated outputs at this point.
6165 std::vector<audio_io_handle_t> outputsClosed;
6166 for (size_t i = 0; i < mOutputs.size(); i++) {
6167 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6168 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6169 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6170 outputsClosed.push_back(desc->mIoHandle);
6171 desc->close();
6172 }
6173 }
6174 for (auto output : outputsClosed) {
6175 removeOutput(output);
6176 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006177}
6178
Eric Laurent98e38192018-02-15 18:31:53 -08006179void AudioPolicyManager::addOutput(audio_io_handle_t output,
6180 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006181{
Eric Laurent1c333e22014-05-20 10:48:17 -07006182 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006183 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006184 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006185 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006186 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006187}
6188
François Gaffie53615e22015-03-19 09:24:12 +01006189void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6190{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006191 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6192 ALOGV("%s: removing primary output", __func__);
6193 mPrimaryOutput = nullptr;
6194 }
François Gaffie53615e22015-03-19 09:24:12 +01006195 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006196 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006197}
6198
Eric Laurent98e38192018-02-15 18:31:53 -08006199void AudioPolicyManager::addInput(audio_io_handle_t input,
6200 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006201{
Eric Laurent1c333e22014-05-20 10:48:17 -07006202 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006203 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006204}
Eric Laurente552edb2014-03-10 17:42:56 -07006205
François Gaffie11d30102018-11-02 16:09:09 +01006206status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006207 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006208 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006209{
François Gaffie11d30102018-11-02 16:09:09 +01006210 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006211 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006212 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006213
François Gaffie11d30102018-11-02 16:09:09 +01006214 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006215 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006216 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006217 }
Eric Laurente552edb2014-03-10 17:42:56 -07006218
Eric Laurent3b73df72014-03-11 09:06:29 -07006219 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006220 // first call getAudioPort to get the supported attributes from the HAL
6221 struct audio_port_v7 port = {};
6222 device->toAudioPort(&port);
6223 status_t status = mpClientInterface->getAudioPort(&port);
6224 if (status == NO_ERROR) {
6225 device->importAudioPort(port);
6226 }
6227
6228 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006229 for (size_t i = 0; i < mOutputs.size(); i++) {
6230 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006231 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006232 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006233 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6234 mOutputs.keyAt(i), device->toString().c_str());
6235 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006236 }
6237 }
6238 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006239 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006240 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006241 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6242 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006243 if (profile->supportsDevice(device)) {
6244 profiles.add(profile);
6245 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6246 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006247 }
6248 }
6249 }
6250
Eric Laurent7b279bb2015-12-14 10:18:23 -08006251 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006252
Eric Laurente552edb2014-03-10 17:42:56 -07006253 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006254 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006255 return BAD_VALUE;
6256 }
6257
6258 // open outputs for matching profiles if needed. Direct outputs are also opened to
6259 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6260 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006261 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006262
6263 // nothing to do if one output is already opened for this profile
6264 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006265 for (j = 0; j < outputs.size(); j++) {
6266 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006267 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006268 // matching profile: save the sample rates, format and channel masks supported
6269 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006270 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006271 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006272 }
Eric Laurente552edb2014-03-10 17:42:56 -07006273 break;
6274 }
6275 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006276 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006277 continue;
6278 }
6279
Eric Laurent3974e3b2017-12-07 17:58:43 -08006280 if (!profile->canOpenNewIo()) {
6281 ALOGW("Max Output number %u already opened for this profile %s",
6282 profile->maxOpenCount, profile->getTagName().c_str());
6283 continue;
6284 }
6285
Eric Laurent83efe1c2017-07-09 16:51:08 -07006286 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07006287 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006288 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6289 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006290 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006291 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006292 profiles.removeAt(profile_index);
6293 profile_index--;
6294 } else {
6295 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006296 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006297 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006298 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6299 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006300 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006301 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006302
François Gaffie11d30102018-11-02 16:09:09 +01006303 if (device_distinguishes_on_address(deviceType)) {
6304 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6305 device->toString().c_str());
6306 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
6307 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006308 }
Eric Laurente552edb2014-03-10 17:42:56 -07006309 ALOGV("checkOutputsForDevice(): adding output %d", output);
6310 }
6311 }
6312
6313 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006314 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006315 return BAD_VALUE;
6316 }
Eric Laurentd4692962014-05-05 18:13:44 -07006317 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006318 // check if one opened output is not needed any more after disconnecting one device
6319 for (size_t i = 0; i < mOutputs.size(); i++) {
6320 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006321 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006322 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006323 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006324 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006325 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006326 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006327 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6328 mOutputs.keyAt(i));
6329 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006330 }
Eric Laurente552edb2014-03-10 17:42:56 -07006331 }
6332 }
Eric Laurentd4692962014-05-05 18:13:44 -07006333 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006334 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006335 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6336 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006337 if (!profile->supportsDevice(device)) {
6338 continue;
6339 }
6340 ALOGV("checkOutputsForDevice(): "
6341 "clearing direct output profile %zu on module %s",
6342 j, hwModule->getName());
6343 profile->clearAudioProfiles();
6344 if (!profile->hasDynamicAudioProfile()) {
6345 continue;
6346 }
6347 // When a device is disconnected, if there is an IOProfile that contains dynamic
6348 // profiles and supports the disconnected device, call getAudioPort to repopulate
6349 // the capabilities of the devices that is supported by the IOProfile.
6350 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6351 if (supportedDevice == device ||
6352 !mAvailableOutputDevices.contains(supportedDevice)) {
6353 continue;
6354 }
6355 struct audio_port_v7 port;
6356 supportedDevice->toAudioPort(&port);
6357 status_t status = mpClientInterface->getAudioPort(&port);
6358 if (status == NO_ERROR) {
6359 supportedDevice->importAudioPort(port);
6360 }
Eric Laurente552edb2014-03-10 17:42:56 -07006361 }
6362 }
6363 }
6364 }
6365 return NO_ERROR;
6366}
6367
François Gaffie11d30102018-11-02 16:09:09 +01006368status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006369 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006370{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006371 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006372
François Gaffie11d30102018-11-02 16:09:09 +01006373 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006374 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006375 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006376 }
6377
Eric Laurentd4692962014-05-05 18:13:44 -07006378 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006379 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006380 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006381 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006382 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006383 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006384 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006385 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006386
François Gaffie11d30102018-11-02 16:09:09 +01006387 if (profile->supportsDevice(device)) {
6388 profiles.add(profile);
6389 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6390 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006391 }
6392 }
6393 }
6394
Eric Laurent0dd51852019-04-19 18:18:58 -07006395 if (profiles.isEmpty()) {
6396 ALOGW("%s: No input profile available for device %s",
6397 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006398 return BAD_VALUE;
6399 }
6400
6401 // open inputs for matching profiles if needed. Direct inputs are also opened to
6402 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6403 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6404
Eric Laurent1c333e22014-05-20 10:48:17 -07006405 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006406
Eric Laurentd4692962014-05-05 18:13:44 -07006407 // nothing to do if one input is already opened for this profile
6408 size_t input_index;
6409 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6410 desc = mInputs.valueAt(input_index);
6411 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006412 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006413 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006414 }
Eric Laurentd4692962014-05-05 18:13:44 -07006415 break;
6416 }
6417 }
6418 if (input_index != mInputs.size()) {
6419 continue;
6420 }
6421
Eric Laurent3974e3b2017-12-07 17:58:43 -08006422 if (!profile->canOpenNewIo()) {
6423 ALOGW("Max Input number %u already opened for this profile %s",
6424 profile->maxOpenCount, profile->getTagName().c_str());
6425 continue;
6426 }
6427
Eric Laurentfe231122017-11-17 17:48:06 -08006428 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006429 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006430 status_t status = desc->open(nullptr,
6431 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006432 AUDIO_SOURCE_MIC,
6433 AUDIO_INPUT_FLAG_NONE,
6434 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006435
Eric Laurentcf2c0212014-07-25 16:20:43 -07006436 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006437 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006438 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006439 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006440 mpClientInterface->setParameters(input, String8(param));
6441 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006442 }
François Gaffie11d30102018-11-02 16:09:09 +01006443 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006444 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006445 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006446 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006447 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006448 }
6449
Eric Laurent0dd51852019-04-19 18:18:58 -07006450 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006451 addInput(input, desc);
6452 }
6453 } // endif input != 0
6454
Eric Laurentcf2c0212014-07-25 16:20:43 -07006455 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006456 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006457 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006458 profiles.removeAt(profile_index);
6459 profile_index--;
6460 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006461 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006462 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006463 }
Eric Laurentd4692962014-05-05 18:13:44 -07006464 ALOGV("checkInputsForDevice(): adding input %d", input);
6465 }
6466 } // end scan profiles
6467
6468 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006469 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006470 return BAD_VALUE;
6471 }
6472 } else {
6473 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006474 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006475 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006476 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006477 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006478 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006479 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006480 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006481 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6482 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006483 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006484 }
6485 }
6486 }
6487 } // end disconnect
6488
6489 return NO_ERROR;
6490}
6491
6492
Eric Laurente0720872014-03-11 09:30:41 -07006493void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006494{
6495 ALOGV("closeOutput(%d)", output);
6496
François Gaffie1c878552018-11-22 16:53:21 +01006497 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6498 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006499 ALOGW("closeOutput() unknown output %d", output);
6500 return;
6501 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006502 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006503 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006504
Eric Laurente552edb2014-03-10 17:42:56 -07006505 // look for duplicated outputs connected to the output being removed.
6506 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006507 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6508 if (dupOutput->isDuplicated() &&
6509 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6510 sp<SwAudioOutputDescriptor> remainingOutput =
6511 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006512 // As all active tracks on duplicated output will be deleted,
6513 // and as they were also referenced on the other output, the reference
6514 // count for their stream type must be adjusted accordingly on
6515 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006516 const bool wasActive = remainingOutput->isActive();
6517 // Note: no-op on the closing output where all clients has already been set inactive
6518 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006519 // stop() will be a no op if the output is still active but is needed in case all
6520 // active streams refcounts where cleared above
6521 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006522 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006523 }
Eric Laurente552edb2014-03-10 17:42:56 -07006524 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6525 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6526
6527 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006528 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006529 }
6530 }
6531
Eric Laurent05b90f82014-08-27 15:32:29 -07006532 nextAudioPortGeneration();
6533
François Gaffie1c878552018-11-22 16:53:21 +01006534 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006535 if (index >= 0) {
6536 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006537 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6538 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006539 mAudioPatches.removeItemsAt(index);
6540 mpClientInterface->onAudioPatchListUpdate();
6541 }
6542
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006543 if (closingOutputWasActive) {
6544 closingOutput->stop();
6545 }
François Gaffie1c878552018-11-22 16:53:21 +01006546 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006547
François Gaffie53615e22015-03-19 09:24:12 +01006548 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006549 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006550 if (closingOutput == mSpatializerOutput) {
6551 mSpatializerOutput.clear();
6552 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006553
6554 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6555 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006556 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006557 bool directOutputOpen = false;
6558 for (size_t i = 0; i < mOutputs.size(); i++) {
6559 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6560 directOutputOpen = true;
6561 break;
6562 }
6563 }
6564 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006565 ALOGV("no direct outputs open, reset MSD patches");
6566 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6567 // how output devices for patching are resolved. Avoid by caching and reusing the
6568 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6569 // devices to patch to. This may be complicated by the fact that devices may become
6570 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006571 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006572 }
6573 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006574}
6575
6576void AudioPolicyManager::closeInput(audio_io_handle_t input)
6577{
6578 ALOGV("closeInput(%d)", input);
6579
6580 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6581 if (inputDesc == NULL) {
6582 ALOGW("closeInput() unknown input %d", input);
6583 return;
6584 }
6585
Eric Laurent6a94d692014-05-20 11:18:06 -07006586 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006587
François Gaffie11d30102018-11-02 16:09:09 +01006588 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006589 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006590 if (index >= 0) {
6591 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006592 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6593 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006594 mAudioPatches.removeItemsAt(index);
6595 mpClientInterface->onAudioPatchListUpdate();
6596 }
6597
Eric Laurentfe231122017-11-17 17:48:06 -08006598 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006599 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006600
François Gaffie11d30102018-11-02 16:09:09 +01006601 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6602 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006603 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006604 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006605 }
Eric Laurente552edb2014-03-10 17:42:56 -07006606}
6607
François Gaffie11d30102018-11-02 16:09:09 +01006608SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6609 const DeviceVector &devices,
6610 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006611{
6612 SortedVector<audio_io_handle_t> outputs;
6613
François Gaffie11d30102018-11-02 16:09:09 +01006614 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006615 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006616 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006617 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006618 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006619 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006620 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006621 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006622 outputs.add(openOutputs.keyAt(i));
6623 }
6624 }
6625 return outputs;
6626}
6627
Mikhail Naganov37977152018-07-11 15:54:44 -07006628void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6629{
6630 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6631 // output is suspended before any tracks are moved to it
6632 checkA2dpSuspend();
6633 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006634 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006635 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006636 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006637 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006638 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6639 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6640 // configuration changes will ultimately be rerouted correctly. We can still avoid
6641 // unnecessary rerouting by caching and reusing the arguments to
6642 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6643 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006644 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006645 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006646 // an event that changed routing likely occurred, inform upper layers
6647 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006648}
6649
François Gaffiec005e562018-11-06 15:04:49 +01006650bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6651 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006652{
François Gaffiec005e562018-11-06 15:04:49 +01006653 return mEngine->getProductStrategyForAttributes(lAttr) ==
6654 mEngine->getProductStrategyForAttributes(rAttr);
6655}
6656
Francois Gaffieff1eb522020-05-06 18:37:04 +02006657void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6658{
6659 for (size_t i = 0; i < mAudioSources.size(); i++) {
6660 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6661 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006662 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006663 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006664 connectAudioSource(sourceDesc);
6665 }
6666 }
6667}
6668
6669void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6670{
6671 for (size_t i = 0; i < mAudioSources.size(); i++) {
6672 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6673 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6674 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6675 disconnectAudioSource(sourceDesc);
6676 }
6677 }
6678}
6679
François Gaffiec005e562018-11-06 15:04:49 +01006680void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6681{
6682 auto psId = mEngine->getProductStrategyForAttributes(attr);
6683
6684 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6685 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006686
François Gaffie11d30102018-11-02 16:09:09 +01006687 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6688 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006689
Eric Laurentc209fe42020-06-05 18:11:23 -07006690 uint32_t maxLatency = 0;
Eric Laurent56ed8842022-11-15 16:04:41 +01006691 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006692 // take into account dynamic audio policies related changes: if a client is now associated
6693 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006694 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006695 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6696 if (desc->isDuplicated()) {
6697 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006698 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006699 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6700 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6701 continue;
6702 }
6703 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006704 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006705 client->uid(), client->session(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006706 if (status != OK) {
6707 continue;
6708 }
yucliuf4de36d2020-09-14 14:57:56 -07006709 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006710 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006711 maxLatency = desc->latency();
6712 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006713 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006714 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006715 }
6716 }
6717
Eric Laurent56ed8842022-11-15 16:04:41 +01006718 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006719 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6720 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006721 for (audio_io_handle_t srcOut : srcOutputs) {
6722 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006723 if (desc == nullptr) continue;
6724
6725 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006726 maxLatency = desc->latency();
6727 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006728
Eric Laurent56ed8842022-11-15 16:04:41 +01006729 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006730 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006731 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006732 // a client on a non direct outputs has necessarily a linear PCM format
6733 // so we can call selectOutput() safely
6734 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6735 client->flags(),
6736 client->config().format,
6737 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006738 client->config().sample_rate,
6739 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006740 if (newOutput != srcOut) {
6741 invalidate = true;
6742 break;
6743 }
6744 } else {
6745 sp<IOProfile> profile = getProfileForOutput(newDevices,
6746 client->config().sample_rate,
6747 client->config().format,
6748 client->config().channel_mask,
6749 client->flags(),
6750 true /* directOnly */);
6751 if (profile != desc->mProfile) {
6752 invalidate = true;
6753 break;
6754 }
6755 }
6756 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006757 // mute strategy while moving tracks from one output to another
6758 if (invalidate) {
6759 invalidatedOutputs.push_back(desc);
6760 if (desc->isStrategyActive(psId)) {
6761 setStrategyMute(psId, true, desc);
6762 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6763 newDevices.types());
6764 }
Eric Laurente552edb2014-03-10 17:42:56 -07006765 }
François Gaffiec005e562018-11-06 15:04:49 +01006766 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006767 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006768 connectAudioSource(source);
6769 }
Eric Laurente552edb2014-03-10 17:42:56 -07006770 }
6771
Eric Laurent56ed8842022-11-15 16:04:41 +01006772 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6773 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6774 std::to_string(srcOutputs[0]).c_str(),
6775 std::to_string(dstOutputs[0]).c_str());
6776
François Gaffiec005e562018-11-06 15:04:49 +01006777 // Move effects associated to this stream from previous output to new output
6778 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006779 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006780 }
François Gaffiec005e562018-11-06 15:04:49 +01006781 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006782 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006783 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006784 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006785 desc->setTracksInvalidatedStatusByStrategy(psId);
6786 }
Eric Laurente552edb2014-03-10 17:42:56 -07006787 }
6788 }
6789}
6790
Eric Laurente0720872014-03-11 09:30:41 -07006791void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006792{
François Gaffiec005e562018-11-06 15:04:49 +01006793 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6794 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6795 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006796 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006797 }
Eric Laurente552edb2014-03-10 17:42:56 -07006798}
6799
Kevin Rocard153f92d2018-12-18 18:33:28 -08006800void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08006801 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006802 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006803 for (size_t i = 0; i < mOutputs.size(); i++) {
6804 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6805 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006806 sp<AudioPolicyMix> primaryMix;
6807 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006808 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006809 client->uid(), client->session(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006810 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6811 for (auto &secondaryMix : secondaryMixes) {
6812 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6813 if (outputDesc != nullptr &&
6814 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6815 secondaryDescs.push_back(outputDesc);
6816 }
6817 }
6818
jiabinc44b3462022-12-08 12:52:31 -08006819 if (status != OK &&
6820 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
6821 // When it failed to query secondary output, only invalidate the client that is not
6822 // MMAP. The reason is that MMAP stream will not support secondary output.
6823 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00006824 } else if (!std::equal(
6825 client->getSecondaryOutputs().begin(),
6826 client->getSecondaryOutputs().end(),
6827 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006828 if (!audio_is_linear_pcm(client->config().format)) {
6829 // If the format is not PCM, the tracks should be invalidated to get correct
6830 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08006831 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00006832 } else {
6833 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6834 std::vector<audio_io_handle_t> secondaryOutputIds;
6835 for (const auto &secondaryDesc: secondaryDescs) {
6836 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6837 weakSecondaryDescs.push_back(secondaryDesc);
6838 }
6839 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6840 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006841 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006842 }
6843 }
6844 }
jiabin10a03f12021-05-07 23:46:28 +00006845 if (!trackSecondaryOutputs.empty()) {
6846 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6847 }
jiabinc44b3462022-12-08 12:52:31 -08006848 if (!clientsToInvalidate.empty()) {
6849 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
6850 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006851 }
6852}
6853
Eric Laurent2517af32020-11-25 15:31:27 +01006854bool AudioPolicyManager::isScoRequestedForComm() const {
6855 AudioDeviceTypeAddrVector devices;
6856 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6857 for (const auto &device : devices) {
6858 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6859 return true;
6860 }
6861 }
6862 return false;
6863}
6864
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006865bool AudioPolicyManager::isHearingAidUsedForComm() const {
6866 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6867 true /*fromCache*/);
6868 for (const auto &device : devices) {
6869 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6870 return true;
6871 }
6872 }
6873 return false;
6874}
6875
6876
Eric Laurente0720872014-03-11 09:30:41 -07006877void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006878{
François Gaffie53615e22015-03-19 09:24:12 +01006879 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006880 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006881 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006882 return;
6883 }
6884
Eric Laurent3a4311c2014-03-17 12:00:47 -07006885 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006886 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6887 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006888 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006889
6890 // if suspended, restore A2DP output if:
6891 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006892 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006893 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006894 //
Eric Laurentf732e072016-08-03 19:30:28 -07006895 // if not suspended, suspend A2DP output if:
6896 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006897 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006898 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006899 //
6900 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006901 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006902 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006903 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006904 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006905
6906 mpClientInterface->restoreOutput(a2dpOutput);
6907 mA2dpSuspended = false;
6908 }
6909 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006910 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006911 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006912 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006913 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006914
6915 mpClientInterface->suspendOutput(a2dpOutput);
6916 mA2dpSuspended = true;
6917 }
6918 }
6919}
6920
François Gaffie11d30102018-11-02 16:09:09 +01006921DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6922 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006923{
François Gaffie11d30102018-11-02 16:09:09 +01006924 DeviceVector devices;
6925
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006926 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006927 if (index >= 0) {
6928 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006929 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006930 ALOGV("%s device %s forced by patch %d", __func__,
6931 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6932 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006933 }
6934 }
6935
Dean Wheatley514b4312020-06-17 21:45:00 +10006936 // Do not retrieve engine device for outputs through MSD
6937 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6938 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6939 return outputDesc->devices();
6940 }
6941
Eric Laurent97ac8712018-07-27 18:59:02 -07006942 // Honor explicit routing requests only if no client using default routing is active on this
6943 // input: a specific app can not force routing for other apps by setting a preferred device.
6944 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006945 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006946 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006947 if (device != nullptr) {
6948 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006949 }
6950
François Gaffiea807ef92018-11-05 10:44:33 +01006951 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6952 // of setForceUse / Default Bus device here
6953 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6954 if (device != nullptr) {
6955 return DeviceVector(device);
6956 }
6957
François Gaffiec005e562018-11-06 15:04:49 +01006958 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6959 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6960 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306961 auto hasStreamActive = [&](auto stream) {
6962 return hasStream(streams, stream) && isStreamActive(stream, 0);
6963 };
Eric Laurent484e9272018-06-07 17:29:23 -07006964
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306965 auto doGetOutputDevicesForVoice = [&]() {
6966 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006967 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306968 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006969 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6970 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306971 };
6972
6973 // With low-latency playing on speaker, music on WFD, when the first low-latency
6974 // output is stopped, getNewOutputDevices checks for a product strategy
6975 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006976 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306977 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6978 // stream is associated to the output descriptor.
6979 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6980 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6981 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6982 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006983 // Retrieval of devices for voice DL is done on primary output profile, cannot
6984 // check the route (would force modifying configuration file for this profile)
6985 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6986 break;
6987 }
Eric Laurente552edb2014-03-10 17:42:56 -07006988 }
François Gaffiec005e562018-11-06 15:04:49 +01006989 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006990 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006991}
6992
François Gaffie11d30102018-11-02 16:09:09 +01006993sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6994 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006995{
François Gaffie11d30102018-11-02 16:09:09 +01006996 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006997
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006998 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006999 if (index >= 0) {
7000 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007001 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007002 ALOGV("getNewInputDevice() device %s forced by patch %d",
7003 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7004 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007005 }
7006 }
7007
Eric Laurent97ac8712018-07-27 18:59:02 -07007008 // Honor explicit routing requests only if no client using default routing is active on this
7009 // input: a specific app can not force routing for other apps by setting a preferred device.
7010 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007011 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7012 if (device != nullptr) {
7013 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007014 }
7015
Eric Laurentdc95a252018-04-12 12:46:56 -07007016 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007017 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007018 audio_attributes_t attributes;
7019 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007020 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007021 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7022 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007023 attributes = topClient->attributes();
7024 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007025 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007026 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007027 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7028 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007029 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007030 }
7031
Francois Gaffie716e1432019-01-14 16:58:59 +01007032 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7033 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007034 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007035 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007036 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007037 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007038
Eric Laurente552edb2014-03-10 17:42:56 -07007039 return device;
7040}
7041
Eric Laurent794fde22016-03-11 09:50:45 -08007042bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7043 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007044 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007045}
7046
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007047status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007048 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007049 if (devices == nullptr) {
7050 return BAD_VALUE;
7051 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007052
Andy Hung6d23c0f2022-02-16 09:37:15 -08007053 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007054 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7055 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007056 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007057 for (const auto& device : curDevices) {
7058 devices->push_back(device->getDeviceTypeAddr());
7059 }
7060 return NO_ERROR;
7061}
7062
Eric Laurente0720872014-03-11 09:30:41 -07007063void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007064 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007065 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007066 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007067 updateDevicesAndOutputs();
7068 break;
7069 default:
7070 break;
7071 }
7072}
7073
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007074uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007075
7076 // skip beacon mute management if a dedicated TTS output is available
7077 if (mTtsOutputAvailable) {
7078 return 0;
7079 }
7080
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007081 switch(event) {
7082 case STARTING_OUTPUT:
7083 mBeaconMuteRefCount++;
7084 break;
7085 case STOPPING_OUTPUT:
7086 if (mBeaconMuteRefCount > 0) {
7087 mBeaconMuteRefCount--;
7088 }
7089 break;
7090 case STARTING_BEACON:
7091 mBeaconPlayingRefCount++;
7092 break;
7093 case STOPPING_BEACON:
7094 if (mBeaconPlayingRefCount > 0) {
7095 mBeaconPlayingRefCount--;
7096 }
7097 break;
7098 }
7099
7100 if (mBeaconMuteRefCount > 0) {
7101 // any playback causes beacon to be muted
7102 return setBeaconMute(true);
7103 } else {
7104 // no other playback: unmute when beacon starts playing, mute when it stops
7105 return setBeaconMute(mBeaconPlayingRefCount == 0);
7106 }
7107}
7108
7109uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7110 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7111 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7112 // keep track of muted state to avoid repeating mute/unmute operations
7113 if (mBeaconMuted != mute) {
7114 // mute/unmute AUDIO_STREAM_TTS on all outputs
7115 ALOGV("\t muting %d", mute);
7116 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007117 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7118 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7119 ALOGV("\t no tts volume source available");
7120 return 0;
7121 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007122 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007123 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007124 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007125 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007126 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007127 maxLatency = latency;
7128 }
7129 }
7130 mBeaconMuted = mute;
7131 return maxLatency;
7132 }
7133 return 0;
7134}
7135
Eric Laurente0720872014-03-11 09:30:41 -07007136void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007137{
François Gaffiec005e562018-11-06 15:04:49 +01007138 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007139 mPreviousOutputs = mOutputs;
7140}
7141
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007142uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007143 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007144 uint32_t delayMs)
7145{
7146 // mute/unmute strategies using an incompatible device combination
7147 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7148 // if unmuting, unmute only after the specified delay
7149 if (outputDesc->isDuplicated()) {
7150 return 0;
7151 }
7152
7153 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007154 DeviceVector devices = outputDesc->devices();
7155 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007156
François Gaffiec005e562018-11-06 15:04:49 +01007157 auto productStrategies = mEngine->getOrderedProductStrategies();
7158 for (const auto &productStrategy : productStrategies) {
7159 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7160 DeviceVector curDevices =
7161 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7162 curDevices = curDevices.filter(outputDesc->supportedDevices());
7163 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007164 bool doMute = false;
7165
François Gaffiec005e562018-11-06 15:04:49 +01007166 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007167 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007168 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7169 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007170 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007171 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007172 }
Eric Laurent99401132014-05-07 19:48:15 -07007173 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007174 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007175 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007176 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007177 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007178 continue;
7179 }
François Gaffiec005e562018-11-06 15:04:49 +01007180 ALOGVV("%s() %s (curDevice %s)", __func__,
7181 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7182 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7183 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007184 if (mute) {
7185 // FIXME: should not need to double latency if volume could be applied
7186 // immediately by the audioflinger mixer. We must account for the delay
7187 // between now and the next time the audioflinger thread for this output
7188 // will process a buffer (which corresponds to one buffer size,
7189 // usually 1/2 or 1/4 of the latency).
7190 if (muteWaitMs < desc->latency() * 2) {
7191 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007192 }
7193 }
7194 }
7195 }
7196 }
7197 }
7198
Eric Laurent99401132014-05-07 19:48:15 -07007199 // temporary mute output if device selection changes to avoid volume bursts due to
7200 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007201 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007202 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007203
Eric Laurentdc462862016-07-19 12:29:53 -07007204 if (muteWaitMs < tempMuteWaitMs) {
7205 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007206 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007207
7208 // If recommended duration is defined, replace temporary mute duration to avoid
7209 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7210 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7211 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7212 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7213 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7214
François Gaffieaaac0fd2018-11-22 17:56:39 +01007215 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7216 // make sure that we do not start the temporary mute period too early in case of
7217 // delayed device change
7218 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7219 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007220 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007221 }
7222 }
7223
Eric Laurente552edb2014-03-10 17:42:56 -07007224 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7225 if (muteWaitMs > delayMs) {
7226 muteWaitMs -= delayMs;
7227 usleep(muteWaitMs * 1000);
7228 return muteWaitMs;
7229 }
7230 return 0;
7231}
7232
François Gaffie11d30102018-11-02 16:09:09 +01007233uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7234 const DeviceVector &devices,
7235 bool force,
7236 int delayMs,
7237 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02007238 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07007239{
jiabin3ff8d7d2022-12-13 06:27:44 +00007240 // TODO(b/262404095): Consider if the output need to be reopened.
François Gaffie11d30102018-11-02 16:09:09 +01007241 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007242 uint32_t muteWaitMs;
7243
7244 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01007245 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
7246 nullptr /* patchHandle */, requiresMuteCheck);
7247 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
7248 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07007249 return muteWaitMs;
7250 }
Eric Laurente552edb2014-03-10 17:42:56 -07007251
7252 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007253 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007254 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007255 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007256
François Gaffie11d30102018-11-02 16:09:09 +01007257 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7258
7259 if (!filteredDevices.isEmpty()) {
7260 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007261 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007262
7263 // if the outputs are not materially active, there is no need to mute.
7264 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007265 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007266 } else {
7267 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7268 muteWaitMs = 0;
7269 }
Eric Laurente552edb2014-03-10 17:42:56 -07007270
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007271 bool outputRouted = outputDesc->isRouted();
7272
Eric Laurent79ea9582020-06-11 18:49:24 -07007273 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7274 // output profile or if new device is not supported AND previous device(s) is(are) still
7275 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007276 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007277 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7278 // restore previous device after evaluating strategy mute state
7279 outputDesc->setDevices(prevDevices);
7280 return muteWaitMs;
7281 }
7282
Eric Laurente552edb2014-03-10 17:42:56 -07007283 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007284 // the requested device is AUDIO_DEVICE_NONE
7285 // OR the requested device is the same as current device
7286 // AND force is not specified
7287 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007288 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007289 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007290 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7291 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007292 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7293 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7294 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7295 }
Eric Laurente552edb2014-03-10 17:42:56 -07007296 return muteWaitMs;
7297 }
7298
François Gaffie11d30102018-11-02 16:09:09 +01007299 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007300
Eric Laurente552edb2014-03-10 17:42:56 -07007301 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007302 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007303 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007304 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007305 PatchBuilder patchBuilder;
7306 patchBuilder.addSource(outputDesc);
7307 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7308 for (const auto &filteredDevice : filteredDevices) {
7309 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007310 }
7311
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007312 // Add half reported latency to delayMs when muteWaitMs is null in order
7313 // to avoid disordered sequence of muting volume and changing devices.
7314 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7315 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007316 }
Eric Laurente552edb2014-03-10 17:42:56 -07007317
7318 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007319 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007320
7321 return muteWaitMs;
7322}
7323
Eric Laurentc75307b2015-03-17 15:29:32 -07007324status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007325 int delayMs,
7326 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007327{
Eric Laurent6a94d692014-05-20 11:18:06 -07007328 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007329 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7330 return INVALID_OPERATION;
7331 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007332 if (patchHandle) {
7333 index = mAudioPatches.indexOfKey(*patchHandle);
7334 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007335 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007336 }
7337 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007338 return INVALID_OPERATION;
7339 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007340 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007341 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007342 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007343 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007344 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007345 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007346 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007347 return status;
7348}
7349
7350status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007351 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007352 bool force,
7353 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007354{
7355 status_t status = NO_ERROR;
7356
Eric Laurent1f2f2232014-06-02 12:01:23 -07007357 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007358 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7359 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007360
François Gaffie11d30102018-11-02 16:09:09 +01007361 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007362 PatchBuilder patchBuilder;
7363 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007364 // AUDIO_SOURCE_HOTWORD is for internal use only:
7365 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007366 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7367 auto result = usecase;
7368 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7369 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7370 }
7371 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007372 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007373 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007374 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007375 }
7376 }
7377 return status;
7378}
7379
Eric Laurent6a94d692014-05-20 11:18:06 -07007380status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7381 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007382{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007383 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007384 ssize_t index;
7385 if (patchHandle) {
7386 index = mAudioPatches.indexOfKey(*patchHandle);
7387 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007388 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007389 }
7390 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007391 return INVALID_OPERATION;
7392 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007393 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007394 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007395 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007396 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007397 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007398 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007399 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007400 return status;
7401}
7402
François Gaffie11d30102018-11-02 16:09:09 +01007403sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007404 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007405 audio_format_t& format,
7406 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007407 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007408{
7409 // Choose an input profile based on the requested capture parameters: select the first available
7410 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007411 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007412 //
7413 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7414 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007415
Atneya Nair0f0a8032022-12-12 16:20:12 -08007416 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7417 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7418 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7419
7420 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007421
jiabin2fd710d2022-05-02 23:20:22 +00007422 for (;;) {
7423 sp<IOProfile> firstInexact = nullptr;
7424 uint32_t updatedSamplingRate = 0;
7425 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7426 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7427 for (const auto& hwModule : mHwModules) {
7428 for (const auto& profile : hwModule->getInputProfiles()) {
7429 // profile->log();
7430 //updatedFormat = format;
7431 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7432 &samplingRate /*updatedSamplingRate*/,
7433 format,
7434 &format, /*updatedFormat*/
7435 channelMask,
7436 &channelMask /*updatedChannelMask*/,
7437 // FIXME ugly cast
7438 (audio_output_flags_t) flags,
7439 true /*exactMatchRequiredForInputFlags*/)) {
7440 return profile;
7441 }
7442 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7443 samplingRate,
7444 &updatedSamplingRate,
7445 format,
7446 &updatedFormat,
7447 channelMask,
7448 &updatedChannelMask,
7449 // FIXME ugly cast
7450 (audio_output_flags_t) flags,
7451 false /*exactMatchRequiredForInputFlags*/)) {
7452 firstInexact = profile;
7453 }
7454 }
7455 }
7456
7457 if (firstInexact != nullptr) {
7458 samplingRate = updatedSamplingRate;
7459 format = updatedFormat;
7460 channelMask = updatedChannelMask;
7461 return firstInexact;
7462 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7463 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7464 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7465 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7466 flags = AUDIO_INPUT_FLAG_NONE;
7467 } else { // fail
7468 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7469 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7470 samplingRate, format, channelMask, oriFlags);
7471 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007472 }
7473 }
jiabin2fd710d2022-05-02 23:20:22 +00007474
7475 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007476}
7477
François Gaffieaaac0fd2018-11-22 17:56:39 +01007478float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7479 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007480 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007481 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007482{
jiabin9a3361e2019-10-01 09:38:30 -07007483 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007484
7485 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7486 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7487 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7488 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007489 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7490 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7491 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7492 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7493 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007494
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007495 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007496 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7497 mOutputs.isActive(ringVolumeSrc, 0)) {
7498 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007499 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007500 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007501 }
7502
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007503 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007504 if ((volumeSource != callVolumeSrc && (isInCall() ||
7505 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007506 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007507 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7508 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007509 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7510 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7511 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007512 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007513 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007514 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007515 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007516 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007517 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007518 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7519 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7520 // programmatically muted.
7521 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7522 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7523 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007524 bool exemptFromCapping =
7525 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7526 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007527 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7528 volumeSource, volumeDb);
7529 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007530 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7531 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7532 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007533 }
7534 }
Eric Laurente552edb2014-03-10 17:42:56 -07007535 // if a headset is connected, apply the following rules to ring tones and notifications
7536 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007537 // - always attenuate notifications volume by 6dB
7538 // - attenuate ring tones volume by 6dB unless music is not playing and
7539 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007540 // - if music is playing, always limit the volume to current music volume,
7541 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007542 if (!Intersection(deviceTypes,
7543 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7544 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007545 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7546 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007547 ((volumeSource == alarmVolumeSrc ||
7548 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007549 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7550 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7551 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007552 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7553 curves.canBeMuted()) {
7554
Eric Laurente552edb2014-03-10 17:42:56 -07007555 // when the phone is ringing we must consider that music could have been paused just before
7556 // by the music application and behave as if music was active if the last music track was
7557 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007558 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007559 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007560 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007561 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007562 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7563 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007564 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007565 float musicVolDb = computeVolume(musicCurves,
7566 musicVolumeSrc,
7567 musicCurves.getVolumeIndex(musicDevice),
7568 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007569 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7570 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7571 if (volumeDb > minVolDb) {
7572 volumeDb = minVolDb;
7573 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007574 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007575 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7576 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7577 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007578 // on A2DP, also ensure notification volume is not too low compared to media when
7579 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007580 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007581 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007582 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7583 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007584 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7585 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007586 }
7587 }
jiabin9a3361e2019-10-01 09:38:30 -07007588 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007589 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007590 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007591 }
7592 }
7593
François Gaffie43c73442018-11-08 08:21:55 +01007594 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007595}
7596
Eric Laurent3839bc02018-07-10 18:33:34 -07007597int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007598 VolumeSource fromVolumeSource,
7599 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007600{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007601 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007602 return srcIndex;
7603 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007604 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7605 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007606 float minSrc = (float)srcCurves.getVolumeIndexMin();
7607 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7608 float minDst = (float)dstCurves.getVolumeIndexMin();
7609 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007610
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007611 // preserve mute request or correct range
7612 if (srcIndex < minSrc) {
7613 if (srcIndex == 0) {
7614 return 0;
7615 }
7616 srcIndex = minSrc;
7617 } else if (srcIndex > maxSrc) {
7618 srcIndex = maxSrc;
7619 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007620 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7621}
7622
François Gaffieaaac0fd2018-11-22 17:56:39 +01007623status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7624 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007625 int index,
7626 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007627 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007628 int delayMs,
7629 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007630{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007631 // do not change actual attributes volume if the attributes is muted
7632 if (outputDesc->isMuted(volumeSource)) {
7633 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7634 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007635 return NO_ERROR;
7636 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007637 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7638 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7639 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7640 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007641
Eric Laurent2517af32020-11-25 15:31:27 +01007642 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007643 bool isHAUsed = isHearingAidUsedForComm();
7644
Eric Laurente552edb2014-03-10 17:42:56 -07007645 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007646 // if sco and call follow same curves, bypass forceUseForComm
7647 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007648 ((isVoiceVolSrc && isScoRequested) ||
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007649 (isBtScoVolSrc && !(isScoRequested || isHAUsed)))) {
Eric Laurent2517af32020-11-25 15:31:27 +01007650 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007651 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007652 // Do not return an error here as AudioService will always set both voice call
7653 // and bluetooth SCO volumes due to stream aliasing.
7654 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007655 }
jiabin9a3361e2019-10-01 09:38:30 -07007656 if (deviceTypes.empty()) {
7657 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007658 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007659
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007660 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7661 ALOGE("invalid volume index range");
7662 return BAD_VALUE;
7663 }
7664
jiabin9a3361e2019-10-01 09:38:30 -07007665 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7666 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007667 // Force VoIP volume to max for bluetooth SCO device except if muted
7668 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007669 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007670 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007671 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007672 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007673 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007674 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007675
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007676 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007677 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007678 // 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 +01007679 if (isVoiceVolSrc) {
7680 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007681 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007682 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007683 }
Eric Laurent18fba842016-03-31 14:41:26 -07007684 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007685 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7686 mLastVoiceVolume = voiceVolume;
7687 }
7688 }
Eric Laurente552edb2014-03-10 17:42:56 -07007689 return NO_ERROR;
7690}
7691
Eric Laurentc75307b2015-03-17 15:29:32 -07007692void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007693 const DeviceTypeSet& deviceTypes,
7694 int delayMs,
7695 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007696{
jiabincd510522020-01-22 09:40:55 -08007697 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007698 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7699 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7700 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007701 curves.getVolumeIndex(deviceTypes),
7702 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007703 }
7704}
7705
François Gaffiec005e562018-11-06 15:04:49 +01007706void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7707 bool on,
7708 const sp<AudioOutputDescriptor>& outputDesc,
7709 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007710 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007711{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007712 std::vector<VolumeSource> sourcesToMute;
7713 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7714 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7715 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007716 VolumeSource source = toVolumeSource(attributes, false);
7717 if ((source != VOLUME_SOURCE_NONE) &&
7718 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7719 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007720 sourcesToMute.push_back(source);
7721 }
Eric Laurente552edb2014-03-10 17:42:56 -07007722 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007723 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007724 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007725 }
7726
Eric Laurente552edb2014-03-10 17:42:56 -07007727}
7728
François Gaffieaaac0fd2018-11-22 17:56:39 +01007729void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7730 bool on,
7731 const sp<AudioOutputDescriptor>& outputDesc,
7732 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007733 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007734{
jiabin9a3361e2019-10-01 09:38:30 -07007735 if (deviceTypes.empty()) {
7736 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007737 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007738 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007739 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007740 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007741 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007742 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007743 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7744 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007745 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007746 }
7747 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007748 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7749 // ignored
7750 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007751 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007752 if (!outputDesc->isMuted(volumeSource)) {
7753 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007754 return;
7755 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007756 if (outputDesc->decMuteCount(volumeSource) == 0) {
7757 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007758 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007759 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007760 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007761 delayMs);
7762 }
7763 }
7764}
7765
François Gaffie53615e22015-03-19 09:24:12 +01007766bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7767{
François Gaffiec005e562018-11-06 15:04:49 +01007768 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007769 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7770 return true;
7771 }
7772
7773 // has known usage?
7774 switch (paa->usage) {
7775 case AUDIO_USAGE_UNKNOWN:
7776 case AUDIO_USAGE_MEDIA:
7777 case AUDIO_USAGE_VOICE_COMMUNICATION:
7778 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7779 case AUDIO_USAGE_ALARM:
7780 case AUDIO_USAGE_NOTIFICATION:
7781 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7782 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7783 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7784 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7785 case AUDIO_USAGE_NOTIFICATION_EVENT:
7786 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7787 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7788 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7789 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007790 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007791 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007792 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007793 case AUDIO_USAGE_EMERGENCY:
7794 case AUDIO_USAGE_SAFETY:
7795 case AUDIO_USAGE_VEHICLE_STATUS:
7796 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007797 break;
7798 default:
7799 return false;
7800 }
7801 return true;
7802}
7803
François Gaffie2110e042015-03-24 08:41:51 +01007804audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7805{
7806 return mEngine->getForceUse(usage);
7807}
7808
Eric Laurent96d1dda2022-03-14 17:14:19 +01007809bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007810 return isStateInCall(mEngine->getPhoneState());
7811}
7812
Eric Laurent96d1dda2022-03-14 17:14:19 +01007813bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007814 return is_state_in_call(state);
7815}
7816
Eric Laurentf9cccec2022-11-16 19:12:00 +01007817bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007818 audio_mode_t mode = mEngine->getPhoneState();
7819 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007820 || (mode == AUDIO_MODE_CALL_SCREEN)
7821 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007822}
7823
Eric Laurentf9cccec2022-11-16 19:12:00 +01007824bool AudioPolicyManager::isInCallOrScreening() const {
7825 audio_mode_t mode = mEngine->getPhoneState();
7826 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7827}
7828
Eric Laurentd60560a2015-04-10 11:31:20 -07007829void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7830{
7831 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007832 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007833 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007834 sourceDesc->sinkDevice()->equals(deviceDesc))
7835 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007836 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007837 }
7838 }
7839
7840 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7841 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7842 bool release = false;
7843 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7844 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7845 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7846 source->ext.device.type == deviceDesc->type()) {
7847 release = true;
7848 }
7849 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007850 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007851 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7852 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7853 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007854 sink->ext.device.type == deviceDesc->type() &&
7855 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7856 || strncmp(sink->ext.device.address, address,
7857 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007858 release = true;
7859 }
7860 }
7861 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007862 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7863 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007864 }
7865 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007866
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007867 mInputs.clearSessionRoutesForDevice(deviceDesc);
7868
Francois Gaffie716e1432019-01-14 16:58:59 +01007869 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007870}
7871
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007872void AudioPolicyManager::modifySurroundFormats(
7873 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007874 std::unordered_set<audio_format_t> enforcedSurround(
7875 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007876 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7877 for (const auto& pair : mConfig.getSurroundFormats()) {
7878 allSurround.insert(pair.first);
7879 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7880 }
Phil Burk09bc4612016-02-24 15:58:15 -08007881
7882 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7883 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007884 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007885 // This is the resulting set of formats depending on the surround mode:
7886 // 'all surround' = allSurround
7887 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7888 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7889 // 'manual surround' = mManualSurroundFormats
7890 // AUTO: formats v 'enforced surround'
7891 // ALWAYS: formats v 'all surround' v 'enforced surround'
7892 // NEVER: formats ^ 'non-surround'
7893 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007894
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007895 std::unordered_set<audio_format_t> formatSet;
7896 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7897 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007898 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007899 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007900 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007901 formatSet.insert(*formatIter);
7902 }
7903 }
7904 } else {
7905 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7906 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007907 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007908
jiabin81772902018-04-02 17:52:27 -07007909 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007910 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007911 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7912 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7913 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007914 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007915 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7916 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7917 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007918 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007919 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007920 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007921 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007922 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007923 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007924}
7925
jiabin06e4bab2019-07-29 10:13:34 -07007926void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7927 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007928 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7929 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7930
7931 // If NEVER, then remove support for channelMasks > stereo.
7932 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007933 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7934 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007935 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007936 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007937 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007938 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007939 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007940 }
7941 }
jiabin81772902018-04-02 17:52:27 -07007942 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7943 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7944 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007945 bool supports5dot1 = false;
7946 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007947 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007948 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7949 supports5dot1 = true;
7950 break;
7951 }
7952 }
7953 // If not then add 5.1 support.
7954 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007955 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007956 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007957 }
Phil Burk09bc4612016-02-24 15:58:15 -08007958 }
7959}
7960
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007961void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007962 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007963 AudioProfileVector &profiles)
7964{
7965 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007966 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007967
François Gaffie112b0af2015-11-19 16:13:25 +01007968 // Format MUST be checked first to update the list of AudioProfile
7969 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007970 reply = mpClientInterface->getParameters(
7971 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007972 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007973 AudioParameter repliedParameters(reply);
7974 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007975 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007976 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7977 return;
7978 }
Phil Burk09bc4612016-02-24 15:58:15 -08007979 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007980 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007981 if (device == AUDIO_DEVICE_OUT_HDMI
7982 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007983 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007984 }
jiabin3e277cc2019-09-10 14:27:34 -07007985 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007986 }
François Gaffie112b0af2015-11-19 16:13:25 +01007987
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007988 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007989 ChannelMaskSet channelMasks;
7990 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007991 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007992 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007993
7994 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007995 reply = mpClientInterface->getParameters(
7996 ioHandle,
7997 requestedParameters.toString() + ";" +
7998 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007999 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008000 AudioParameter repliedParameters(reply);
8001 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008002 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008003 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01008004 }
8005 }
8006 if (profiles.hasDynamicChannelsFor(format)) {
8007 reply = mpClientInterface->getParameters(ioHandle,
8008 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07008009 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01008010 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008011 AudioParameter repliedParameters(reply);
8012 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008013 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008014 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008015 if (device == AUDIO_DEVICE_OUT_HDMI
8016 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008017 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07008018 }
François Gaffie112b0af2015-11-19 16:13:25 +01008019 }
8020 }
jiabin3e277cc2019-09-10 14:27:34 -07008021 addDynamicAudioProfileAndSort(
8022 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01008023 }
8024}
Eric Laurentd60560a2015-04-10 11:31:20 -07008025
Mikhail Naganovdc769682018-05-04 15:34:08 -07008026status_t AudioPolicyManager::installPatch(const char *caller,
8027 audio_patch_handle_t *patchHandle,
8028 AudioIODescriptorInterface *ioDescriptor,
8029 const struct audio_patch *patch,
8030 int delayMs)
8031{
8032 ssize_t index = mAudioPatches.indexOfKey(
8033 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8034 *patchHandle : ioDescriptor->getPatchHandle());
8035 sp<AudioPatch> patchDesc;
8036 status_t status = installPatch(
8037 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8038 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008039 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008040 }
8041 return status;
8042}
8043
8044status_t AudioPolicyManager::installPatch(const char *caller,
8045 ssize_t index,
8046 audio_patch_handle_t *patchHandle,
8047 const struct audio_patch *patch,
8048 int delayMs,
8049 uid_t uid,
8050 sp<AudioPatch> *patchDescPtr)
8051{
8052 sp<AudioPatch> patchDesc;
8053 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8054 if (index >= 0) {
8055 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008056 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008057 }
8058
8059 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8060 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8061 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8062 if (status == NO_ERROR) {
8063 if (index < 0) {
8064 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008065 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008066 } else {
8067 patchDesc->mPatch = *patch;
8068 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008069 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008070 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008071 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008072 }
8073 nextAudioPortGeneration();
8074 mpClientInterface->onAudioPatchListUpdate();
8075 }
8076 if (patchDescPtr) *patchDescPtr = patchDesc;
8077 return status;
8078}
8079
jiabinbce0c1d2020-10-05 11:20:18 -07008080bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8081{
8082 const TrackClientVector activeClients = output->getActiveClients();
8083 if (activeClients.empty()) {
8084 return true;
8085 }
8086 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8087 if (index < 0) {
8088 ALOGE("%s, no audio patch found while there are active clients on output %d",
8089 __func__, output->getId());
8090 return false;
8091 }
8092 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8093 DeviceVector routedDevices;
8094 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8095 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8096 patchDesc->mPatch.sinks[i].id);
8097 if (device == nullptr) {
8098 ALOGE("%s, no audio device found with id(%d)",
8099 __func__, patchDesc->mPatch.sinks[i].id);
8100 return false;
8101 }
8102 routedDevices.add(device);
8103 }
8104 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008105 if (client->isInvalid()) {
8106 // No need to take care about invalidated clients.
8107 continue;
8108 }
jiabinbce0c1d2020-10-05 11:20:18 -07008109 sp<DeviceDescriptor> preferredDevice =
8110 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8111 if (mEngine->getOutputDevicesForAttributes(
8112 client->attributes(), preferredDevice, false) == routedDevices) {
8113 return false;
8114 }
8115 }
8116 return true;
8117}
8118
8119sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008120 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008121 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8122 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008123{
8124 for (const auto& device : devices) {
8125 // TODO: This should be checking if the profile supports the device combo.
8126 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008127 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8128 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008129 return nullptr;
8130 }
8131 }
8132 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8133 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008134 status_t status = desc->open(halConfig, mixerConfig, devices,
8135 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008136 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008137 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008138 return nullptr;
8139 }
8140
8141 // Here is where the out_set_parameters() for card & device gets called
8142 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8143 const audio_devices_t deviceType = device->type();
8144 const String8 &address = String8(device->address().c_str());
8145 if (!address.isEmpty()) {
8146 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8147 mpClientInterface->setParameters(output, String8(param));
8148 free(param);
8149 }
8150 updateAudioProfiles(device, output, profile->getAudioProfiles());
8151 if (!profile->hasValidAudioProfile()) {
8152 ALOGW("%s() missing param", __func__);
8153 desc->close();
8154 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008155 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8156 // Reopen the output with the best audio profile picked by APM when the profile supports
8157 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008158 desc->close();
8159 output = AUDIO_IO_HANDLE_NONE;
8160 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8161 profile->pickAudioProfile(
8162 config.sample_rate, config.channel_mask, config.format);
8163 config.offload_info.sample_rate = config.sample_rate;
8164 config.offload_info.channel_mask = config.channel_mask;
8165 config.offload_info.format = config.format;
8166
jiabina84c3d32022-12-02 18:59:55 +00008167 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008168 if (status != NO_ERROR) {
8169 return nullptr;
8170 }
8171 }
8172
8173 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008174
baek.kim -61c20122022-07-27 10:05:32 +00008175 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8176 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8177
jiabinbce0c1d2020-10-05 11:20:18 -07008178 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8179 sp<AudioPolicyMix> policyMix;
8180 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8181 policyMix->setOutput(desc);
8182 desc->mPolicyMix = policyMix;
8183 } else {
8184 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
8185 address.string());
8186 }
8187
baek.kim -61c20122022-07-27 10:05:32 +00008188 } else if (hasPrimaryOutput() && speaker != nullptr
8189 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008190 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8191 // no duplicated output for:
8192 // - direct outputs
8193 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008194 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008195 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8196
8197 //TODO: configure audio effect output stage here
8198
8199 // open a duplicating output thread for the new output and the primary output
8200 sp<SwAudioOutputDescriptor> dupOutputDesc =
8201 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8202 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8203 if (status == NO_ERROR) {
8204 // add duplicated output descriptor
8205 addOutput(duplicatedOutput, dupOutputDesc);
8206 } else {
8207 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8208 mPrimaryOutput->mIoHandle, output);
8209 desc->close();
8210 removeOutput(output);
8211 nextAudioPortGeneration();
8212 return nullptr;
8213 }
8214 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008215 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8216 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8217 mPrimaryOutput = desc;
8218 }
jiabinbce0c1d2020-10-05 11:20:18 -07008219 return desc;
8220}
8221
jiabinf1c73972022-04-14 16:28:52 -07008222status_t AudioPolicyManager::getDevicesForAttributes(
8223 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8224 // Devices are determined in the following precedence:
8225 //
8226 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8227 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8228 //
8229 // If no such dynamic policy then
8230 // 2) Devices containing an active client using setPreferredDevice
8231 // with same strategy as the attributes.
8232 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8233 //
8234 // If no corresponding active client with setPreferredDevice then
8235 // 3) Devices associated with the strategy determined by the attributes
8236 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8237 //
8238 // See related getOutputForAttrInt().
8239
8240 // check dynamic policies but only for primary descriptors (secondary not used for audible
8241 // audio routing, only used for duplication for playback capture)
8242 sp<AudioPolicyMix> policyMix;
8243 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02008244 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE, policyMix,
jiabinf1c73972022-04-14 16:28:52 -07008245 nullptr /* secondaryMixes */);
8246 if (status != OK) {
8247 return status;
8248 }
8249
8250 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8251 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8252 // as they are unaffected by device/stream volume
8253 // (per SwAudioOutputDescriptor::isFixedVolume()).
8254 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8255 ) {
8256 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8257 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8258 devices.add(deviceDesc);
8259 } else {
8260 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8261 // which selects setPreferredDevice if active. This means forVolume call
8262 // will take an active setPreferredDevice, if such exists.
8263
8264 devices = mEngine->getOutputDevicesForAttributes(
8265 attr, nullptr /* preferredDevice */, false /* fromCache */);
8266 }
8267
8268 if (forVolume) {
8269 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8270 // for single volume control in AudioService (such relationship should exist if
8271 // SPEAKER_SAFE is present).
8272 //
8273 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8274 DeviceVector speakerSafeDevices =
8275 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8276 if (!speakerSafeDevices.isEmpty()) {
8277 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8278 devices.remove(speakerSafeDevices);
8279 }
8280 }
8281
8282 return NO_ERROR;
8283}
8284
8285status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8286 AudioProfileVector& audioProfiles,
8287 uint32_t flags,
8288 bool isInput) {
8289 for (const auto& hwModule : mHwModules) {
8290 // the MSD module checks for different conditions
8291 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8292 continue;
8293 }
8294 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8295 : hwModule->getOutputProfiles();
8296 for (const auto& profile : ioProfiles) {
8297 if (!profile->areAllDevicesSupported(devices) ||
8298 !profile->isCompatibleProfileForFlags(
8299 flags, false /*exactMatchRequiredForInputFlags*/)) {
8300 continue;
8301 }
8302 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8303 }
8304 }
8305
8306 if (!isInput) {
8307 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8308 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8309 if (msdModule != nullptr) {
8310 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8311 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8312 for (const auto &profile: msdModule->getOutputProfiles()) {
8313 if (!profile->asAudioPort()->isDirectOutput()) {
8314 continue;
8315 }
8316 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8317 }
8318 } else {
8319 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8320 }
8321 }
8322 }
8323
8324 return NO_ERROR;
8325}
8326
jiabin3ff8d7d2022-12-13 06:27:44 +00008327sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8328 const audio_config_t *config,
8329 audio_output_flags_t flags,
8330 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008331 closeOutput(outputDesc->mIoHandle);
8332 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8333 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8334 if (preferredOutput == nullptr) {
8335 ALOGE("%s failed to reopen output device=%d, caller=%s",
8336 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008337 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008338 return preferredOutput;
8339}
8340
8341void AudioPolicyManager::reopenOutputsWithDevices(
8342 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8343 for (const auto& [output, devices] : outputsToReopen) {
8344 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8345 closeOutput(output);
8346 openOutputWithProfileAndDevice(desc->mProfile, devices);
8347 }
jiabina84c3d32022-12-02 18:59:55 +00008348}
8349
jiabinc44b3462022-12-08 12:52:31 -08008350PortHandleVector AudioPolicyManager::getClientsForStream(
8351 audio_stream_type_t streamType) const {
8352 PortHandleVector clients;
8353 for (size_t i = 0; i < mOutputs.size(); ++i) {
8354 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8355 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8356 }
8357 return clients;
8358}
8359
8360void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8361 PortHandleVector clients;
8362 for (auto stream : streams) {
8363 PortHandleVector clientsForStream = getClientsForStream(stream);
8364 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8365 }
8366 mpClientInterface->invalidateTracks(clients);
8367}
8368
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008369} // namespace android