blob: 7489bf953465823997fea5fbb8140a6dc6cc877a [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
Oscar Azucena873d10f2023-01-12 18:34:42 -08001171 bool usePrimaryOutputFromPolicyMixes = false;
1172
Kevin Rocard153f92d2018-12-18 18:33:28 -08001173 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1174 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1175 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001176 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001177 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1178 .channel_mask = config->channel_mask,
1179 .format = config->format,
1180 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001181 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001182 mAvailableOutputDevices, requestedDevice, primaryMix,
1183 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001184 if (status != OK) {
1185 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001186 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001187
Kevin Rocard153f92d2018-12-18 18:33:28 -08001188 // 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));
jiabin5eaf0962022-12-20 20:11:38 +00001284 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1285 // and it is currently active.
1286 if (info != nullptr && info->getUid() != uid &&
1287 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1288 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001289 info = nullptr;
1290 }
1291 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001292 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001293 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001294 // The client will be active if the client is currently preferred mixer owner and the
1295 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001296 *isBitPerfect = (info != nullptr
1297 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001298 && info->getUid() == uid
1299 && *output != AUDIO_IO_HANDLE_NONE
1300 // When bit-perfect output is selected for the preferred mixer attributes owner,
1301 // only need to consider the config matches.
1302 && mOutputs.valueFor(*output)->isConfigurationMatched(
1303 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001304 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001305 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001306 AudioProfileVector profiles;
1307 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1308 if (ret == NO_ERROR && !profiles.empty()) {
1309 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
1310 : *profiles[0]->getChannels().begin();
1311 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
1312 : *profiles[0]->getSampleRates().begin();
1313 config->format = profiles[0]->getFormat();
1314 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001315 return INVALID_OPERATION;
1316 }
Paul McLeanaa981192015-03-21 09:55:15 -07001317
François Gaffiec005e562018-11-06 15:04:49 +01001318 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001319 for (auto &outputDevice : outputDevices) {
1320 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1321 *selectedDeviceId = outputDevice->getId();
1322 break;
1323 }
1324 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001325
Eric Laurent8a1095a2019-11-08 14:44:16 -08001326 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1327 *outputType = API_OUTPUT_TELEPHONY_TX;
1328 } else {
1329 *outputType = API_OUTPUT_LEGACY;
1330 }
1331
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001332 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1333
1334 return NO_ERROR;
1335}
1336
1337status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1338 audio_io_handle_t *output,
1339 audio_session_t session,
1340 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001341 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001342 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001343 audio_output_flags_t *flags,
1344 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001345 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001346 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001347 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001348 bool *isSpatialized,
1349 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001350{
1351 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1352 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1353 return INVALID_OPERATION;
1354 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001355 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001356 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001357 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001358 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001359 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001360 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001361 const sp<DeviceDescriptor> requestedDevice =
1362 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1363
1364 // Prevent from storing invalid requested device id in clients
1365 const audio_port_handle_t sanitizedRequestedPortId =
1366 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1367 *selectedDeviceId = sanitizedRequestedPortId;
1368
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001369 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001370 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001371 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1372 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001373 if (status != NO_ERROR) {
1374 return status;
1375 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001376 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001377 if (secondaryOutputs != nullptr) {
1378 for (auto &secondaryMix : secondaryMixes) {
1379 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1380 if (outputDesc != nullptr &&
1381 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1382 secondaryOutputs->push_back(outputDesc->mIoHandle);
1383 weakSecondaryOutputDescs.push_back(outputDesc);
1384 }
1385 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001386 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001387
Eric Laurent8fc147b2018-07-22 19:13:55 -07001388 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001389 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001390 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001391 };
jiabin4ef93452019-09-10 14:29:54 -07001392 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001393
Eric Laurentc209fe42020-06-05 18:11:23 -07001394 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001395 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001396 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001397 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001398 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001399 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001400 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001401 std::move(weakSecondaryOutputDescs),
1402 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001403 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001404
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001405 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1406 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001407
Eric Laurente83b55d2014-11-14 10:06:21 -08001408 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001409}
1410
Eric Laurentc529cf62020-04-17 18:19:10 -07001411status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1412 audio_session_t session,
1413 const audio_config_t *config,
1414 audio_output_flags_t flags,
1415 const DeviceVector &devices,
1416 audio_io_handle_t *output) {
1417
1418 *output = AUDIO_IO_HANDLE_NONE;
1419
1420 // skip direct output selection if the request can obviously be attached to a mixed output
1421 // and not explicitly requested
1422 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1423 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1424 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1425 return NAME_NOT_FOUND;
1426 }
1427
1428 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1429 // This prevents creating an offloaded track and tearing it down immediately after start
1430 // when audioflinger detects there is an active non offloadable effect.
1431 // FIXME: We should check the audio session here but we do not have it in this context.
1432 // This may prevent offloading in rare situations where effects are left active by apps
1433 // in the background.
1434 sp<IOProfile> profile;
1435 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1436 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1437 profile = getProfileForOutput(
1438 devices, config->sample_rate, config->format, config->channel_mask,
1439 flags, true /* directOnly */);
1440 }
1441
1442 if (profile == nullptr) {
1443 return NAME_NOT_FOUND;
1444 }
1445
1446 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1447 for (size_t i = 0; i < mOutputs.size(); i++) {
1448 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1449 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1450 // reuse direct output if currently open by the same client
1451 // and configured with same parameters
1452 if ((config->sample_rate == desc->getSamplingRate()) &&
1453 (config->format == desc->getFormat()) &&
1454 (config->channel_mask == desc->getChannelMask()) &&
1455 (session == desc->mDirectClientSession)) {
1456 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001457 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001458 mOutputs.keyAt(i), session);
1459 *output = mOutputs.keyAt(i);
1460 return NO_ERROR;
1461 }
1462 }
1463 }
1464
1465 if (!profile->canOpenNewIo()) {
1466 return NAME_NOT_FOUND;
1467 }
1468
1469 sp<SwAudioOutputDescriptor> outputDesc =
1470 new SwAudioOutputDescriptor(profile, mpClientInterface);
1471
Michael Chan6fb34492020-12-08 15:44:49 +11001472 // An MSD patch may be using the only output stream that can service this request. Release
1473 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001474 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001475
Eric Laurentf1f22e72021-07-13 14:04:14 +02001476 status_t status =
1477 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001478
1479 // only accept an output with the requested parameters
1480 if (status != NO_ERROR ||
1481 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1482 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1483 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1484 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1485 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1486 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1487 config->channel_mask, outputDesc->getChannelMask());
1488 if (*output != AUDIO_IO_HANDLE_NONE) {
1489 outputDesc->close();
1490 }
1491 // fall back to mixer output if possible when the direct output could not be open
1492 if (audio_is_linear_pcm(config->format) &&
1493 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1494 return NAME_NOT_FOUND;
1495 }
1496 *output = AUDIO_IO_HANDLE_NONE;
1497 return BAD_VALUE;
1498 }
1499 outputDesc->mDirectOpenCount = 1;
1500 outputDesc->mDirectClientSession = session;
1501
1502 addOutput(*output, outputDesc);
1503 mPreviousOutputs = mOutputs;
1504 ALOGV("%s returns new direct output %d", __func__, *output);
1505 mpClientInterface->onAudioPortListUpdate();
1506 return NO_ERROR;
1507}
1508
François Gaffie11d30102018-11-02 16:09:09 +01001509audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1510 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001511 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001512 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001513 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001514 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001515 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001516 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001517 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001518{
Andy Hungc88b0642018-04-27 15:42:35 -07001519 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001520
jiabine375d412019-02-26 12:54:53 -08001521 // Discard haptic channel mask when forcing muting haptic channels.
1522 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001523 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1524 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001525
Eric Laurente552edb2014-03-10 17:42:56 -07001526 // open a direct output if required by specified parameters
1527 //force direct flag if offload flag is set: offloading implies a direct output stream
1528 // and all common behaviors are driven by checking only the direct flag
1529 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001530 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1531 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001532 }
Nadav Bar766fb022018-01-07 12:18:03 +02001533 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1534 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001535 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001536
1537 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1538
Eric Laurente83b55d2014-11-14 10:06:21 -08001539 // only allow deep buffering for music stream type
1540 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001541 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001542 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001543 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001544 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1545 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001546 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001547 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001548 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001549 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001550 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001551 audio_is_linear_pcm(config->format) &&
1552 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001553 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001554 AUDIO_OUTPUT_FLAG_DIRECT);
1555 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001556 }
Eric Laurente552edb2014-03-10 17:42:56 -07001557
Carter Hsua3abb402021-10-26 11:11:20 +08001558 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1559 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1560 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1561 }
1562
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001563 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001564 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001565 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001566 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001567 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001568 }
1569
Eric Laurentc529cf62020-04-17 18:19:10 -07001570 audio_config_t directConfig = *config;
1571 directConfig.channel_mask = channelMask;
1572 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1573 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001574 return output;
1575 }
1576
Eric Laurent14cbfca2016-03-17 09:42:16 -07001577 // A request for HW A/V sync cannot fallback to a mixed output because time
1578 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001579 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001580 return AUDIO_IO_HANDLE_NONE;
1581 }
1582
Eric Laurente552edb2014-03-10 17:42:56 -07001583 // ignoring channel mask due to downmix capability in mixer
1584
1585 // open a non direct output
1586
1587 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001588 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001589 // get which output is suitable for the specified stream. The actual
1590 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001591 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001592 if (prefMixerConfigInfo != nullptr) {
1593 for (audio_io_handle_t outputHandle : outputs) {
1594 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1595 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1596 output = outputHandle;
1597 break;
1598 }
1599 }
1600 if (output == AUDIO_IO_HANDLE_NONE) {
1601 // No output open with the preferred profile. Open a new one.
1602 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1603 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1604 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1605 config.format = prefMixerConfigInfo->getConfigBase().format;
1606 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1607 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1608 &config, prefMixerConfigInfo->getFlags());
1609 if (preferredOutput == nullptr) {
1610 ALOGE("%s failed to open output with preferred mixer config", __func__);
1611 } else {
1612 output = preferredOutput->mIoHandle;
1613 }
1614 }
1615 } else {
1616 // at this stage we should ignore the DIRECT flag as no direct output could be
1617 // found earlier
1618 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1619 output = selectOutput(
1620 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1621 }
Eric Laurente552edb2014-03-10 17:42:56 -07001622 }
François Gaffie11d30102018-11-02 16:09:09 +01001623 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001624 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001625 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001626
Eric Laurente552edb2014-03-10 17:42:56 -07001627 return output;
1628}
1629
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001630sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001631 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1632 mAvailableInputDevices);
1633 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1634}
1635
1636DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1637 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1638 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001639}
1640
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001641const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001642 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001643 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1644 if (msdModule != 0) {
1645 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1646 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1647 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1648 const struct audio_port_config *source = &patch->mPatch.sources[j];
1649 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1650 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001651 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001652 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001653 }
1654 }
1655 }
1656 return msdPatches;
1657}
1658
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001659bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1660 ssize_t index = mAudioPatches.indexOfKey(handle);
1661 if (index < 0) {
1662 return false;
1663 }
1664 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1665 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1666 if (msdModule == nullptr) {
1667 return false;
1668 }
1669 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1670 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1671 return true;
1672 }
1673 index = getMsdOutputPatches().indexOfKey(handle);
1674 if (index < 0) {
1675 return false;
1676 }
1677 return true;
1678}
1679
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001680status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1681 const InputProfileCollection &inputProfiles,
1682 const OutputProfileCollection &outputProfiles,
1683 const sp<DeviceDescriptor> &sourceDevice,
1684 const sp<DeviceDescriptor> &sinkDevice,
1685 AudioProfileVector& sourceProfiles,
1686 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001687 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001688 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001689 return NO_INIT;
1690 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001691 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001692 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001693 return NO_INIT;
1694 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001695 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001696 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1697 inProfile->supportsDevice(sourceDevice)) {
1698 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001699 }
1700 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001701 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001702 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001703 outProfile->supportsDevice(sinkDevice)) {
1704 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001705 }
1706 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001707 return NO_ERROR;
1708}
1709
1710status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1711 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1712 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1713{
Dean Wheatley16809da2022-12-09 14:55:46 +11001714 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1715 static const std::vector<audio_format_t> formatsOrder = {{
1716 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1717 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1718 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1719 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1720 // preferred).
1721 std::vector<audio_channel_mask_t> masks = {{
1722 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1723 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1724 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1725 // insert index masks (higher counts most preferred) as preferred over position masks
1726 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1727 masks.insert(
1728 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1729 }
1730 return masks;
1731 }();
1732
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001733 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001734 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1735 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001736 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001737 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1738 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001739 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001740 }
1741 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1742 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1743 sinkConfig->format = bestSinkConfig.format;
1744 // For encoded streams force direct flag to prevent downstream mixing.
1745 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1746 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001747 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1748 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001749 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001750 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1751 // raw and IEC61937 framed streams.
1752 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1753 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1754 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001755 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1756 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001757 sourceConfig->channel_mask =
1758 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1759 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1760 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001761 sourceConfig->format = bestSinkConfig.format;
1762 // Copy input stream directly without any processing (e.g. resampling).
1763 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1764 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1765 if (hwAvSync) {
1766 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1767 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1768 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1769 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1770 }
1771 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1772 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1773 sinkConfig->config_mask |= config_mask;
1774 sourceConfig->config_mask |= config_mask;
1775 return NO_ERROR;
1776}
1777
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001778PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1779 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001780{
1781 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001782 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1783 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1784 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1785 if (deviceModule == nullptr) {
1786 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1787 return patchBuilder;
1788 }
1789 const InputProfileCollection inputProfiles = msdIsSource ?
1790 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1791 const OutputProfileCollection outputProfiles = msdIsSource ?
1792 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1793
1794 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1795 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1796 device : getMsdAudioOutDevices().itemAt(0);
1797 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1798
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001799 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1800 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001801 AudioProfileVector sourceProfiles;
1802 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001803 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1804 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001805 for (auto hwAvSync : { true, false }) {
1806 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1807 sourceProfiles, sinkProfiles) != NO_ERROR) {
1808 continue;
1809 }
1810 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1811 &sinkConfig) == NO_ERROR) {
1812 // Found a matching config. Re-create PatchBuilder with this config.
1813 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1814 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001815 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001816 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001817 " supporting PCM format conversion.", __func__);
1818 return patchBuilder;
1819}
1820
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001821status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001822 DeviceVector devices;
1823 if (outputDevices != nullptr && outputDevices->size() > 0) {
1824 devices.add(*outputDevices);
1825 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001826 // Use media strategy for unspecified output device. This should only
1827 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1828 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001829 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001830 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001831 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001832 }
Michael Chan6fb34492020-12-08 15:44:49 +11001833 std::vector<PatchBuilder> patchesToCreate;
1834 for (auto i = 0u; i < devices.size(); ++i) {
1835 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001836 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001837 }
1838 // Retain only the MSD patches associated with outputDevices request.
1839 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001840 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001841 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1842 auto retainedPatch = false;
1843 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1844 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1845 patchesToRemove.removeItemsAt(i);
1846 retainedPatch = true;
1847 break;
1848 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001849 }
Michael Chan6fb34492020-12-08 15:44:49 +11001850 if (retainedPatch) {
1851 it = patchesToCreate.erase(it);
1852 continue;
1853 }
1854 ++it;
1855 }
1856 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1857 return NO_ERROR;
1858 }
1859 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1860 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001861 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001862 }
Michael Chan6fb34492020-12-08 15:44:49 +11001863 status_t status = NO_ERROR;
1864 for (const auto &p : patchesToCreate) {
1865 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1866 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1867 char message[256];
1868 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1869 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1870 currStatus == NO_ERROR ? "Success" : "Error",
1871 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1872 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1873 if (currStatus == NO_ERROR) {
1874 ALOGD("%s", message);
1875 } else {
1876 ALOGE("%s", message);
1877 if (status == NO_ERROR) {
1878 status = currStatus;
1879 }
1880 }
1881 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001882 return status;
1883}
1884
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001885void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1886 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001887 for (size_t i = 0; i < msdPatches.size(); i++) {
1888 const auto& patch = msdPatches[i];
1889 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1890 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1891 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1892 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1893 releaseAudioPatch(patch->getHandle(), mUidCached);
1894 break;
1895 }
1896 }
1897 }
1898}
1899
Dorin Drimus94d94412022-02-02 09:05:02 +01001900bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1901 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1902 AudioPatchCollection msdPatches = getMsdOutputPatches();
1903 for (size_t i = 0; i < msdPatches.size(); i++) {
1904 const auto& patch = msdPatches[i];
1905 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1906 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1907 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1908 const auto& foundDevice = devicesToCheck.getDevice(
1909 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1910 if (foundDevice != nullptr) {
1911 devicesToCheck.remove(foundDevice);
1912 if (devicesToCheck.isEmpty()) {
1913 return true;
1914 }
1915 }
1916 }
1917 }
1918 }
1919 return false;
1920}
1921
Eric Laurente0720872014-03-11 09:30:41 -07001922audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001923 audio_output_flags_t flags,
1924 audio_format_t format,
1925 audio_channel_mask_t channelMask,
1926 uint32_t samplingRate,
1927 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001928{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001929 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1930 "%s called with format %#x", __func__, format);
1931
jiabinebb6af42020-06-09 17:31:17 -07001932 // Return the output that haptic-generating attached to when 1) session id is specified,
1933 // 2) haptic-generating effect exists for given session id and 3) the output that
1934 // haptic-generating effect attached to is in given outputs.
1935 if (sessionId != AUDIO_SESSION_NONE) {
1936 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1937 sessionId, FX_IID_HAPTICGENERATOR);
1938 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1939 return hapticGeneratingOutput;
1940 }
1941 }
1942
Eric Laurent16c66dd2019-05-01 17:54:10 -07001943 // Flags disqualifying an output: the match must happen before calling selectOutput()
1944 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1945 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1946
1947 // Flags expressing a functional request: must be honored in priority over
1948 // other criteria
1949 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1950 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001951 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1952 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001953 // Flags expressing a performance request: have lower priority than serving
1954 // requested sampling rate or channel mask
1955 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1956 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1957 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1958
1959 const audio_output_flags_t functionalFlags =
1960 (audio_output_flags_t)(flags & kFunctionalFlags);
1961 const audio_output_flags_t performanceFlags =
1962 (audio_output_flags_t)(flags & kPerformanceFlags);
1963
1964 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1965
Eric Laurente552edb2014-03-10 17:42:56 -07001966 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001967 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001968 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001969 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001970 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001971 // with tiebreak preferring the minimum number of extra functional flags
1972 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001973 // 3: the output supporting the exact channel mask
1974 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00001975 // 5: the output with the highest sampling rate if the requested sample rate is
1976 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001977 // 6: the output with the highest number of requested performance flags
1978 // 7: the output with the bit depth the closest to the requested one
1979 // 8: the primary output
1980 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001981
Eric Laurent16c66dd2019-05-01 17:54:10 -07001982 // matching criteria values in priority order for best matching output so far
1983 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001984
Eric Laurent16c66dd2019-05-01 17:54:10 -07001985 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1986 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1987 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001988
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001989 for (audio_io_handle_t output : outputs) {
1990 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001991 // matching criteria values in priority order for current output
1992 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001993
Eric Laurent16c66dd2019-05-01 17:54:10 -07001994 if (outputDesc->isDuplicated()) {
1995 continue;
1996 }
1997 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1998 continue;
1999 }
Eric Laurent8838a382014-09-08 16:44:28 -07002000
Eric Laurent16c66dd2019-05-01 17:54:10 -07002001 // If haptic channel is specified, use the haptic output if present.
2002 // When using haptic output, same audio format and sample rate are required.
2003 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002004 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002005 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2006 continue;
2007 }
2008 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002009 && format == outputDesc->getFormat()
2010 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002011 currentMatchCriteria[0] = outputHapticChannelCount;
2012 }
2013
2014 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002015 const int matchingFunctionalFlags =
2016 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2017 const int totalFunctionalFlags =
2018 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2019 // Prefer matching functional flags, but subtract unnecessary functional flags.
2020 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002021
2022 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002023 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2024 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002025 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2026 channelCount <= outputChannelCount) {
2027 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002028 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2029 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002030 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002031 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002032 currentMatchCriteria[3] = outputChannelCount;
2033 }
2034
2035 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002036 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002037 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002038 }
2039
2040 // performance flags match
2041 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2042
2043 // format match
2044 if (format != AUDIO_FORMAT_INVALID) {
2045 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002046 PolicyAudioPort::kFormatDistanceMax -
2047 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002048 }
2049
2050 // primary output match
2051 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2052
2053 // compare match criteria by priority then value
2054 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2055 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2056 bestMatchCriteria = currentMatchCriteria;
2057 bestOutput = output;
2058
2059 std::stringstream result;
2060 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2061 std::ostream_iterator<int>(result, " "));
2062 ALOGV("%s new bestOutput %d criteria %s",
2063 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002064 }
2065 }
2066
Eric Laurent16c66dd2019-05-01 17:54:10 -07002067 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002068}
2069
Eric Laurent8fc147b2018-07-22 19:13:55 -07002070status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002071{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002072 ALOGV("%s portId %d", __FUNCTION__, portId);
2073
2074 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2075 if (outputDesc == 0) {
2076 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002077 return BAD_VALUE;
2078 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002079 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002080
Eric Laurent8fc147b2018-07-22 19:13:55 -07002081 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002082 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002083
Eric Laurent733ce942017-12-07 12:18:25 -08002084 status_t status = outputDesc->start();
2085 if (status != NO_ERROR) {
2086 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002087 }
2088
Eric Laurent97ac8712018-07-27 18:59:02 -07002089 uint32_t delayMs;
2090 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002091
2092 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002093 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002094 if (status == DEAD_OBJECT) {
2095 sp<SwAudioOutputDescriptor> desc =
2096 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2097 if (desc == nullptr) {
2098 // This is not common, it may indicate something wrong with the HAL.
2099 ALOGE("%s unable to open output with default config", __func__);
2100 return status;
2101 }
2102 desc->mUsePreferredMixerAttributes = true;
2103 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002104 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002105 }
jiabina84c3d32022-12-02 18:59:55 +00002106
2107 // If the client is the first one active on preferred mixer parameters, reopen the output
2108 // if the current mixer parameters doesn't match the preferred one.
2109 if (outputDesc->devices().size() == 1) {
2110 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2111 outputDesc->devices()[0]->getId(), client->strategy());
2112 if (info != nullptr && info->getUid() == client->uid()) {
2113 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2114 info->getConfigBase(), info->getFlags())) {
2115 stopSource(outputDesc, client);
2116 outputDesc->stop();
2117 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2118 config.channel_mask = info->getConfigBase().channel_mask;
2119 config.sample_rate = info->getConfigBase().sample_rate;
2120 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002121 sp<SwAudioOutputDescriptor> desc =
2122 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2123 if (desc == nullptr) {
2124 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002125 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002126 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002127 // Intentionally return error to let the client side resending request for
2128 // creating and starting.
2129 return DEAD_OBJECT;
2130 }
2131 info->increaseActiveClient();
2132 }
2133 }
2134
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002135 if (client->hasPreferredDevice()) {
2136 // playback activity with preferred device impacts routing occurred, inform upper layers
2137 mpClientInterface->onRoutingUpdated();
2138 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002139 if (delayMs != 0) {
2140 usleep(delayMs * 1000);
2141 }
2142
2143 return status;
2144}
2145
Eric Laurent96d1dda2022-03-14 17:14:19 +01002146bool AudioPolicyManager::isLeUnicastActive() const {
2147 if (isInCall()) {
2148 return true;
2149 }
2150 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2151}
2152
2153bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2154 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2155 return false;
2156 }
2157 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2158 ALOGV("%s active %d", __func__, active);
2159 return active;
2160}
2161
Eric Laurent97ac8712018-07-27 18:59:02 -07002162status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2163 const sp<TrackClientDescriptor>& client,
2164 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002165{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002166 // cannot start playback of STREAM_TTS if any other output is being used
2167 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002168
2169 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002170 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002171 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002172 auto clientStrategy = client->strategy();
2173 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002174 if (stream == AUDIO_STREAM_TTS) {
2175 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002176 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002177 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002178 return INVALID_OPERATION;
2179 } else {
2180 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2181 }
2182 } else {
2183 // some playback other than beacon starts
2184 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2185 }
2186
Eric Laurent77305a62016-07-25 16:39:22 -07002187 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002188 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002189 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002190
François Gaffie11d30102018-11-02 16:09:09 +01002191 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002192 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002193 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002194 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002195 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002196 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002197 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002198 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002199 } else {
2200 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002201 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002202 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2203 AUDIO_FORMAT_DEFAULT);
2204 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2205 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002206 }
2207
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002208 // requiresMuteCheck is false when we can bypass mute strategy.
2209 // It covers a common case when there is no materially active audio
2210 // and muting would result in unnecessary delay and dropped audio.
2211 const uint32_t outputLatencyMs = outputDesc->latency();
2212 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002213 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002214
Eric Laurente552edb2014-03-10 17:42:56 -07002215 // increment usage count for this stream on the requested output:
2216 // NOTE that the usage count is the same for duplicated output and hardware output which is
2217 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002218 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002219
2220 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002221 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2222 client->isPreferredDeviceForExclusiveUse()) {
2223 // Preferred device may be exclusive, use only if no other active clients on this output
2224 devices = DeviceVector(
2225 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2226 } else {
2227 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2228 }
François Gaffie11d30102018-11-02 16:09:09 +01002229 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002230 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002231 }
2232 }
Eric Laurente552edb2014-03-10 17:42:56 -07002233
François Gaffiec005e562018-11-06 15:04:49 +01002234 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002235 selectOutputForMusicEffects();
2236 }
2237
François Gaffie1c878552018-11-22 16:53:21 +01002238 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002239 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002240 if (devices.isEmpty()) {
2241 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002242 }
François Gaffiec005e562018-11-06 15:04:49 +01002243 bool shouldWait =
2244 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2245 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2246 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002247 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002248 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002249 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002250 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002251 // An output has a shared device if
2252 // - managed by the same hw module
2253 // - supports the currently selected device
2254 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002255 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002256
Eric Laurent77305a62016-07-25 16:39:22 -07002257 // force a device change if any other output is:
2258 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002259 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002260 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002261 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002262 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002263 // change the device currently selected by the other output.
2264 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002265 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002266 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002267 force = true;
2268 }
2269 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002270 // a notification so that audio focus effect can propagate, or that a mute/unmute
2271 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002272 const uint32_t latencyMs = desc->latency();
2273 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2274
2275 if (shouldWait && isActive && (waitMs < latencyMs)) {
2276 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002277 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002278
2279 // Require mute check if another output is on a shared device
2280 // and currently active to have proper drain and avoid pops.
2281 // Note restoring AudioTracks onto this output needs to invoke
2282 // a volume ramp if there is no mute.
2283 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002284 }
2285 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002286
jiabin3ff8d7d2022-12-13 06:27:44 +00002287 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2288 // If the output is open with preferred mixer attributes, but the routed device is
2289 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2290 // changed.
2291 return DEAD_OBJECT;
2292 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002293 const uint32_t muteWaitMs =
jiabin3ff8d7d2022-12-13 06:27:44 +00002294 setOutputDevices(outputDesc, devices, force, 0, nullptr, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002295
Eric Laurente552edb2014-03-10 17:42:56 -07002296 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002297 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002298 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002299 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002300 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002301 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002302 outputDesc->useHwGain() /*force*/)) {
2303 // request AudioService to reinitialize the volume curves asynchronously
2304 ALOGE("checkAndSetVolume failed, requesting volume range init");
2305 mpClientInterface->onVolumeRangeInitRequest();
2306 };
Eric Laurente552edb2014-03-10 17:42:56 -07002307
2308 // update the outputs if starting an output with a stream that can affect notification
2309 // routing
2310 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002311
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002312 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002313 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002314 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002315 }
Eric Laurentdc462862016-07-19 12:29:53 -07002316
2317 if (waitMs > muteWaitMs) {
2318 *delayMs = waitMs - muteWaitMs;
2319 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002320
2321 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2322 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2323 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2324 // change occurs after the MixerThread starts and causes a stream volume
2325 // glitch.
2326 //
2327 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002328 }
Eric Laurentdc462862016-07-19 12:29:53 -07002329
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002330 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002331 mEngine->getForceUse(
2332 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002333 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002334 }
2335
Eric Laurent97ac8712018-07-27 18:59:02 -07002336 // Automatically enable the remote submix input when output is started on a re routing mix
2337 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002338 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2339 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002340 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2341 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2342 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002343 "remote-submix",
2344 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002345 }
2346
Eric Laurent96d1dda2022-03-14 17:14:19 +01002347 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2348
Eric Laurente552edb2014-03-10 17:42:56 -07002349 return NO_ERROR;
2350}
2351
Eric Laurent96d1dda2022-03-14 17:14:19 +01002352void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2353 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2354 bool isUnicastActive = isLeUnicastActive();
2355
2356 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002357 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002358 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2359 for (size_t i = 0; i < mOutputs.size(); i++) {
2360 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2361 if (desc != ignoredOutput && desc->isActive()
2362 && ((isUnicastActive &&
2363 !desc->devices().
2364 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2365 || (wasUnicastActive &&
2366 !desc->devices().getDevicesFromTypes(
2367 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2368 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2369 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002370 if (desc->mUsePreferredMixerAttributes && force) {
2371 // If the device is using preferred mixer attributes, the output need to reopen
2372 // with default configuration when the new selected devices are different from
2373 // current routing devices.
2374 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2375 continue;
2376 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002377 setOutputDevices(desc, newDevices, force, delayMs);
2378 // re-apply device specific volume if not done by setOutputDevice()
2379 if (!force) {
2380 applyStreamVolumes(desc, newDevices.types(), delayMs);
2381 }
2382 }
2383 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002384 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002385 }
2386}
2387
Eric Laurent8fc147b2018-07-22 19:13:55 -07002388status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002389{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002390 ALOGV("%s portId %d", __FUNCTION__, portId);
2391
2392 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2393 if (outputDesc == 0) {
2394 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002395 return BAD_VALUE;
2396 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002397 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002398
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002399 if (client->hasPreferredDevice(true)) {
2400 // playback activity with preferred device impacts routing occurred, inform upper layers
2401 mpClientInterface->onRoutingUpdated();
2402 }
2403
Eric Laurent97ac8712018-07-27 18:59:02 -07002404 ALOGV("stopOutput() output %d, stream %d, session %d",
2405 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002406
Eric Laurent97ac8712018-07-27 18:59:02 -07002407 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002408
Eric Laurent733ce942017-12-07 12:18:25 -08002409 if (status == NO_ERROR ) {
2410 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002411 } else {
2412 return status;
2413 }
2414
2415 if (outputDesc->devices().size() == 1) {
2416 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2417 outputDesc->devices()[0]->getId(), client->strategy());
2418 if (info != nullptr && info->getUid() == client->uid()) {
2419 info->decreaseActiveClient();
2420 if (info->getActiveClientCount() == 0) {
2421 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2422 }
2423 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002424 }
2425 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002426}
2427
Eric Laurent97ac8712018-07-27 18:59:02 -07002428status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2429 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002430{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002431 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002432 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002433 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002434 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002435
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002436 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2437
François Gaffie1c878552018-11-22 16:53:21 +01002438 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2439 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002440 // Automatically disable the remote submix input when output is stopped on a
2441 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002442 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002443 if (isSingleDeviceType(
2444 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002445 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002446 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002447 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2448 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002449 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002450 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002451 }
2452 }
2453 bool forceDeviceUpdate = false;
2454 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002455 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002456 forceDeviceUpdate = true;
2457 }
2458
Eric Laurente552edb2014-03-10 17:42:56 -07002459 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002460 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002461
Eric Laurente552edb2014-03-10 17:42:56 -07002462 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002463 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002464 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002465 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002466
2467 // If the routing does not change, if an output is routed on a device using HwGain
2468 // (aka setAudioPortConfig) and there are still active clients following different
2469 // volume group(s), force reapply volume
2470 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2471 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2472
Eric Laurente552edb2014-03-10 17:42:56 -07002473 // delay the device switch by twice the latency because stopOutput() is executed when
2474 // the track stop() command is received and at that time the audio track buffer can
2475 // still contain data that needs to be drained. The latency only covers the audio HAL
2476 // and kernel buffers. Also the latency does not always include additional delay in the
2477 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002478 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2479 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002480
2481 // force restoring the device selection on other active outputs if it differs from the
2482 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002483 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002484 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002485 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002486 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002487 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002488 desc->isActive() &&
2489 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002490 (newDevices != desc->devices())) {
2491 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2492 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002493
jiabin3ff8d7d2022-12-13 06:27:44 +00002494 if (desc->mUsePreferredMixerAttributes && force) {
2495 // If the device is using preferred mixer attributes, the output need to
2496 // reopen with default configuration when the new selected devices are
2497 // different from current routing devices.
2498 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2499 continue;
2500 }
François Gaffie11d30102018-11-02 16:09:09 +01002501 setOutputDevices(desc, newDevices2, force, delayMs);
2502
Eric Laurent57de36c2016-09-28 16:59:11 -07002503 // re-apply device specific volume if not done by setOutputDevice()
2504 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002505 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002506 }
Eric Laurente552edb2014-03-10 17:42:56 -07002507 }
2508 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002509 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002510 // update the outputs if stopping one with a stream that can affect notification routing
2511 handleNotificationRoutingForStream(stream);
2512 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002513
2514 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2515 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002516 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002517 }
2518
François Gaffiec005e562018-11-06 15:04:49 +01002519 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002520 selectOutputForMusicEffects();
2521 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002522
2523 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2524
Eric Laurente552edb2014-03-10 17:42:56 -07002525 return NO_ERROR;
2526 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002527 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002528 return INVALID_OPERATION;
2529 }
2530}
2531
jiabinbce0c1d2020-10-05 11:20:18 -07002532bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002533{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002534 ALOGV("%s portId %d", __FUNCTION__, portId);
2535
2536 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2537 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002538 // If an output descriptor is closed due to a device routing change,
2539 // then there are race conditions with releaseOutput from tracks
2540 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2541 // destroyed shortly thereafter.
2542 //
2543 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002544 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002545 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002546 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002547
2548 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002549
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302550 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2551 if (outputDesc->isClientActive(client)) {
2552 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2553 stopOutput(portId);
2554 }
2555
Eric Laurent8fc147b2018-07-22 19:13:55 -07002556 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2557 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002558 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002559 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002560 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002561 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002562 if (--outputDesc->mDirectOpenCount == 0) {
2563 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002564 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002565 }
2566 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302567
Andy Hung39efb7a2018-09-26 15:39:28 -07002568 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002569 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2570 // The output is pending reopened to query dynamic profiles and
2571 // there is no active clients
2572 closeOutput(outputDesc->mIoHandle);
2573 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2574 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2575 if (newOutputDesc == nullptr) {
2576 ALOGE("%s failed to open output", __func__);
2577 }
2578 return true;
2579 }
2580 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002581}
2582
Eric Laurentcaf7f482014-11-25 17:50:47 -08002583status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2584 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002585 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002586 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002587 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002588 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002589 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002590 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002591 input_type_t *inputType,
2592 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002593{
François Gaffiec005e562018-11-06 15:04:49 +01002594 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002595 "flags %#x attributes=%s requested device ID %d",
2596 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2597 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002598
Eric Laurentad2e7b92017-09-14 20:06:42 -07002599 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002600 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002601 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002602 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002603 sp<AudioInputDescriptor> inputDesc;
2604 sp<RecordClientDescriptor> clientDesc;
2605 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002606 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002607 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002608
2609 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2610 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2611 return INVALID_OPERATION;
2612 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002613
Francois Gaffie716e1432019-01-14 16:58:59 +01002614 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2615 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002616 }
2617
Paul McLean466dc8e2015-04-17 13:15:36 -06002618 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002619 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002620 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002621
Eric Laurentad2e7b92017-09-14 20:06:42 -07002622 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2623 // possible
2624 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2625 *input != AUDIO_IO_HANDLE_NONE) {
2626 ssize_t index = mInputs.indexOfKey(*input);
2627 if (index < 0) {
2628 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2629 status = BAD_VALUE;
2630 goto error;
2631 }
2632 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002633 RecordClientVector clients = inputDesc->getClientsForSession(session);
2634 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002635 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2636 status = BAD_VALUE;
2637 goto error;
2638 }
2639 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2640 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002641 // corresponds to a new client and is only permitted from the same UID.
2642 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002643 if (clients.size() > 1) {
2644 for (const auto& client : clients) {
2645 // The client map is ordered by key values (portId) and portIds are allocated
2646 // incrementaly. So the first client in this list is the one opened by audio flinger
2647 // when the mmap stream is created and should be ignored as it does not correspond
2648 // to an actual client
2649 if (client == *clients.cbegin()) {
2650 continue;
2651 }
2652 if (uid != client->uid() && !client->isSilenced()) {
2653 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2654 uid, client->portId(), client->uid());
2655 status = INVALID_OPERATION;
2656 goto error;
2657 }
Eric Laurent331679c2018-04-16 17:03:16 -07002658 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002659 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002660 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002661 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002662
Eric Laurentfecbceb2021-02-09 14:46:43 +01002663 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002664 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002665 }
2666
2667 *input = AUDIO_IO_HANDLE_NONE;
2668 *inputType = API_INPUT_INVALID;
2669
Francois Gaffie716e1432019-01-14 16:58:59 +01002670 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002671 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002672 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002673 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002674 ALOGW("%s could not find input mix for attr %s",
2675 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002676 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002677 }
jiabinc1de2df2019-05-07 14:26:40 -07002678 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2679 String8(attr->tags + strlen("addr=")),
2680 AUDIO_FORMAT_DEFAULT);
2681 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002682 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002683 __func__, attributes.source, attributes.tags);
2684 status = BAD_VALUE;
2685 goto error;
2686 }
2687
Kevin Rocard25f9b052019-02-27 15:08:54 -08002688 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2689 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2690 } else {
2691 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2692 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002693 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002694 if (explicitRoutingDevice != nullptr) {
2695 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002696 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002697 // Prevent from storing invalid requested device id in clients
2698 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002699 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002700 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2701 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002702 }
François Gaffie11d30102018-11-02 16:09:09 +01002703 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002704 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002705 status = BAD_VALUE;
2706 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002707 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002708 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2709 *inputType = API_INPUT_MIX_CAPTURE;
2710 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002711 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2712 // there is an external policy, but this input is attached to a mix of recorders,
2713 // meaning it receives audio injected into the framework, so the recorder doesn't
2714 // know about it and is therefore considered "legacy"
2715 *inputType = API_INPUT_LEGACY;
2716 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002717 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002718 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002719 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002720 } else {
2721 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002722 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002723
Eric Laurent599c7582015-12-07 18:05:55 -08002724 }
2725
François Gaffiec005e562018-11-06 15:04:49 +01002726 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002727 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002728 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002729 AudioProfileVector profiles;
2730 status_t ret = getProfilesForDevices(
2731 DeviceVector(device), profiles, flags, true /*isInput*/);
2732 if (ret == NO_ERROR && !profiles.empty()) {
2733 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
2734 : *profiles[0]->getChannels().begin();
2735 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
2736 : *profiles[0]->getSampleRates().begin();
2737 config->format = profiles[0]->getFormat();
2738 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002739 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002740 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002741
Eric Laurent8f42ea12018-08-08 09:08:25 -07002742exit:
2743
François Gaffiec005e562018-11-06 15:04:49 +01002744 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2745 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002746
Francois Gaffie716e1432019-01-14 16:58:59 +01002747 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002748 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002749 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002750
Mikhail Naganov2996f672019-04-18 12:29:59 -07002751 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002752 requestedDeviceId, attributes.source, flags,
2753 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002754 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002755 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002756
2757 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2758 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002759
Eric Laurent599c7582015-12-07 18:05:55 -08002760 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002761
2762error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002763 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002764}
2765
2766
François Gaffie11d30102018-11-02 16:09:09 +01002767audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002768 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002769 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002770 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002771 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002772 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002773{
2774 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002775 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002776 bool isSoundTrigger = false;
2777
François Gaffiec005e562018-11-06 15:04:49 +01002778 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002779 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2780 if (index >= 0) {
2781 input = mSoundTriggerSessions.valueFor(session);
2782 isSoundTrigger = true;
2783 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2784 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2785 } else {
2786 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002787 }
François Gaffiec005e562018-11-06 15:04:49 +01002788 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002789 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002790 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002791 }
2792
Carter Hsua3abb402021-10-26 11:11:20 +08002793 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2794 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2795 }
2796
Eric Laurentfe231122017-11-17 17:48:06 -08002797 // sampling rate and flags may be updated by getInputProfile
2798 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2799 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002800 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002801 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002802 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002803 // find a compatible input profile (not necessarily identical in parameters)
2804 sp<IOProfile> profile = getInputProfile(
2805 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2806 if (profile == nullptr) {
2807 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002808 }
jiabin2fd710d2022-05-02 23:20:22 +00002809
Glenn Kasten05ddca52016-02-11 08:17:12 -08002810 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002811 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002812 if (samplingRate == 0) {
2813 samplingRate = profileSamplingRate;
2814 }
Eric Laurente552edb2014-03-10 17:42:56 -07002815
Eric Laurent322b4d22015-04-03 15:57:54 -07002816 if (profile->getModuleHandle() == 0) {
2817 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002818 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002819 }
2820
Eric Laurentec376dc2021-04-08 20:41:22 +02002821 // Reuse an already opened input if a client with the same session ID already exists
2822 // on that input
2823 for (size_t i = 0; i < mInputs.size(); i++) {
2824 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2825 if (desc->mProfile != profile) {
2826 continue;
2827 }
2828 RecordClientVector clients = desc->clientsList();
2829 for (const auto &client : clients) {
2830 if (session == client->session()) {
2831 return desc->mIoHandle;
2832 }
2833 }
2834 }
2835
Eric Laurent3974e3b2017-12-07 17:58:43 -08002836 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002837 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002838 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002839 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002840 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002841 continue;
2842 }
2843 // if sound trigger, reuse input if used by other sound trigger on same session
2844 // else
2845 // reuse input if active client app is not in IDLE state
2846 //
2847 RecordClientVector clients = desc->clientsList();
2848 bool doClose = false;
2849 for (const auto& client : clients) {
2850 if (isSoundTrigger != client->isSoundTrigger()) {
2851 continue;
2852 }
2853 if (client->isSoundTrigger()) {
2854 if (session == client->session()) {
2855 return desc->mIoHandle;
2856 }
2857 continue;
2858 }
2859 if (client->active() && client->appState() != APP_STATE_IDLE) {
2860 return desc->mIoHandle;
2861 }
2862 doClose = true;
2863 }
2864 if (doClose) {
2865 closeInput(desc->mIoHandle);
2866 } else {
2867 i++;
2868 }
2869 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002870 }
2871
Eric Laurentfe231122017-11-17 17:48:06 -08002872 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002873
Eric Laurentfe231122017-11-17 17:48:06 -08002874 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2875 lConfig.sample_rate = profileSamplingRate;
2876 lConfig.channel_mask = profileChannelMask;
2877 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002878
François Gaffie11d30102018-11-02 16:09:09 +01002879 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002880
2881 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002882 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002883 (profileSamplingRate != lConfig.sample_rate) ||
2884 !audio_formats_match(profileFormat, lConfig.format) ||
2885 (profileChannelMask != lConfig.channel_mask)) {
2886 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002887 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002888 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002889 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002890 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002891 }
Eric Laurent599c7582015-12-07 18:05:55 -08002892 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002893 }
2894
Eric Laurentc722f302014-12-10 11:21:49 -08002895 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002896
Eric Laurent599c7582015-12-07 18:05:55 -08002897 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002898 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002899
Eric Laurent599c7582015-12-07 18:05:55 -08002900 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002901}
2902
Eric Laurent4eb58f12018-12-07 16:41:02 -08002903status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002904{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002905 ALOGV("%s portId %d", __FUNCTION__, portId);
2906
2907 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2908 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002909 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002910 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002911 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002912 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002913 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002914 if (client->active()) {
2915 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2916 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002917 }
2918
Eric Laurent8f42ea12018-08-08 09:08:25 -07002919 audio_session_t session = client->session();
2920
Eric Laurent4eb58f12018-12-07 16:41:02 -08002921 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002922
Eric Laurent4eb58f12018-12-07 16:41:02 -08002923 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002924
Eric Laurent4eb58f12018-12-07 16:41:02 -08002925 status_t status = inputDesc->start();
2926 if (status != NO_ERROR) {
2927 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002928 }
Eric Laurente552edb2014-03-10 17:42:56 -07002929
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002930 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002931 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002932 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002933
Eric Laurent8f42ea12018-08-08 09:08:25 -07002934 // indicate active capture to sound trigger service if starting capture from a mic on
2935 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002936 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002937 if (device != nullptr) {
2938 status = setInputDevice(input, device, true /* force */);
2939 } else {
2940 ALOGW("%s no new input device can be found for descriptor %d",
2941 __FUNCTION__, inputDesc->getId());
2942 status = BAD_VALUE;
2943 }
Eric Laurente552edb2014-03-10 17:42:56 -07002944
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002945 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002946 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002947 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002948 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002949 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2950 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002951 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002952 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002953
François Gaffie11d30102018-11-02 16:09:09 +01002954 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2955 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002956 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002957 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002958 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002959
Eric Laurent8f42ea12018-08-08 09:08:25 -07002960 // automatically enable the remote submix output when input is started if not
2961 // used by a policy mix of type MIX_TYPE_RECORDERS
2962 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002963 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002964 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002965 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002966 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002967 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2968 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002969 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002970 if (address != "") {
2971 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2972 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002973 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002974 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002975 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002976 } else if (status != NO_ERROR) {
2977 // Restore client activity state.
2978 inputDesc->setClientActive(client, false);
2979 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002980 }
2981
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002982 ALOGV("%s input %d source = %d status = %d exit",
2983 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002984
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002985 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002986}
2987
Eric Laurent8fc147b2018-07-22 19:13:55 -07002988status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002989{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002990 ALOGV("%s portId %d", __FUNCTION__, portId);
2991
2992 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2993 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002994 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002995 return BAD_VALUE;
2996 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002997 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002998 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002999 if (!client->active()) {
3000 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003001 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003002 }
Carter Hsue6139d52021-07-08 10:30:20 +08003003 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003004 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003005
Eric Laurent8f42ea12018-08-08 09:08:25 -07003006 inputDesc->stop();
3007 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003008 auto current_source = inputDesc->source();
3009 setInputDevice(input, getNewInputDevice(inputDesc),
3010 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003011 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003012 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003013 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003014 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003015 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3016 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003017 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003018 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003019
3020 // automatically disable the remote submix output when input is stopped if not
3021 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003022 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003023 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003024 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003025 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003026 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3027 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003028 }
3029 if (address != "") {
3030 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3031 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003032 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003033 }
3034 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003035 resetInputDevice(input);
3036
3037 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3038 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003039 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3040 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003041 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003042 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003043 }
3044 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003045 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003046 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003047}
3048
Eric Laurent8fc147b2018-07-22 19:13:55 -07003049void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003050{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003051 ALOGV("%s portId %d", __FUNCTION__, portId);
3052
3053 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3054 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003055 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003056 return;
3057 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003058 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003059 audio_io_handle_t input = inputDesc->mIoHandle;
3060
Eric Laurent8f42ea12018-08-08 09:08:25 -07003061 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003062
Andy Hung39efb7a2018-09-26 15:39:28 -07003063 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08003064
Andy Hung39efb7a2018-09-26 15:39:28 -07003065 if (inputDesc->getClientCount() > 0) {
3066 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003067 return;
3068 }
3069
Eric Laurent05b90f82014-08-27 15:32:29 -07003070 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003071 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003072 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003073}
3074
Eric Laurent8f42ea12018-08-08 09:08:25 -07003075void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003076{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003077 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003078
3079 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003080 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003081 }
3082}
3083
Eric Laurent8f42ea12018-08-08 09:08:25 -07003084void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3085{
3086 stopInput(portId);
3087 releaseInput(portId);
3088}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003089
Eric Laurent0dd51852019-04-19 18:18:58 -07003090void AudioPolicyManager::checkCloseInputs() {
3091 // After connecting or disconnecting an input device, close input if:
3092 // - it has no client (was just opened to check profile) OR
3093 // - none of its supported devices are connected anymore OR
3094 // - one of its clients cannot be routed to one of its supported
3095 // devices anymore. Otherwise update device selection
3096 std::vector<audio_io_handle_t> inputsToClose;
3097 for (size_t i = 0; i < mInputs.size(); i++) {
3098 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3099 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003100 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003101 inputsToClose.push_back(mInputs.keyAt(i));
3102 } else {
3103 bool close = false;
3104 for (const auto& client : input->clientsList()) {
3105 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003106 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3107 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003108 if (!input->supportedDevices().contains(device)) {
3109 close = true;
3110 break;
3111 }
3112 }
3113 if (close) {
3114 inputsToClose.push_back(mInputs.keyAt(i));
3115 } else {
3116 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3117 }
3118 }
3119 }
3120
3121 for (const audio_io_handle_t handle : inputsToClose) {
3122 ALOGV("%s closing input %d", __func__, handle);
3123 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003124 }
Eric Laurentd4692962014-05-05 18:13:44 -07003125}
3126
François Gaffie251c7f02018-11-07 10:41:08 +01003127void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003128{
3129 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003130 if (indexMin < 0 || indexMax < 0) {
3131 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3132 return;
3133 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003134 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003135
3136 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003137 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3138 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003139 continue;
3140 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003141 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003142 }
Eric Laurente552edb2014-03-10 17:42:56 -07003143}
3144
Eric Laurente0720872014-03-11 09:30:41 -07003145status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003146 int index,
3147 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003148{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003149 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003150 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3151 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3152 return NO_ERROR;
3153 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003154 ALOGV("%s: stream %s attributes=%s", __func__,
3155 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003156 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003157}
3158
Eric Laurente0720872014-03-11 09:30:41 -07003159status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003160 int *index,
3161 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003162{
François Gaffiec005e562018-11-06 15:04:49 +01003163 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3164 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003165 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003166 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003167 deviceTypes = mEngine->getOutputDevicesForStream(
3168 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003169 }
jiabin9a3361e2019-10-01 09:38:30 -07003170 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003171}
3172
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003173status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003174 int index,
3175 audio_devices_t device)
3176{
3177 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003178 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3179 if (group == VOLUME_GROUP_NONE) {
3180 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003181 return BAD_VALUE;
3182 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003183 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003184 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003185 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003186 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003187 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3188 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3189 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3190 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003191 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3192
3193 status = setVolumeCurveIndex(index, device, curves);
3194 if (status != NO_ERROR) {
3195 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3196 return status;
3197 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003198
jiabin9a3361e2019-10-01 09:38:30 -07003199 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003200 auto curCurvAttrs = curves.getAttributes();
3201 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3202 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003203 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003204 } else if (!curves.getStreamTypes().empty()) {
3205 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003206 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003207 } else {
3208 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3209 return BAD_VALUE;
3210 }
jiabin9a3361e2019-10-01 09:38:30 -07003211 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3212 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003213
François Gaffiecfe17322018-11-07 13:41:29 +01003214 // update volume on all outputs and streams matching the following:
3215 // - The requested stream (or a stream matching for volume control) is active on the output
3216 // - The device (or devices) selected by the engine for this stream includes
3217 // the requested device
3218 // - For non default requested device, currently selected device on the output is either the
3219 // requested device or one of the devices selected by the engine for this stream
3220 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3221 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003222 for (size_t i = 0; i < mOutputs.size(); i++) {
3223 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003224 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003225
jiabin9a3361e2019-10-01 09:38:30 -07003226 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3227 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003228 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003229
3230 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003231 continue;
3232 }
3233 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3234 curDevices.find(device) == curDevices.end()) {
3235 continue;
3236 }
3237 bool applyVolume = false;
3238 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3239 curSrcDevices.insert(device);
3240 applyVolume = (curSrcDevices.find(
3241 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3242 } else {
3243 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3244 }
3245 if (!applyVolume) {
3246 continue; // next output
3247 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003248 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3249 // If a higher priority strategy is active, and the output is routed to a device with a
3250 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003251 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003252 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003253 // If the volume source is active with higher priority source, ensure at least Sw Muted
3254 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003255 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3256 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3257 false /*preferredDevice*/);
3258 if (activeClients.empty()) {
3259 continue;
3260 }
3261 bool isPreempted = false;
3262 bool isHigherPriority = productStrategy < strategy;
3263 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003264 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003265 ALOGV("%s: Strategy=%d (\nrequester:\n"
3266 " group %d, volumeGroup=%d attributes=%s)\n"
3267 " higher priority source active:\n"
3268 " volumeGroup=%d attributes=%s) \n"
3269 " on output %zu, bailing out", __func__, productStrategy,
3270 group, group, toString(attributes).c_str(),
3271 client->volumeSource(), toString(client->attributes()).c_str(), i);
3272 applyVolume = false;
3273 isPreempted = true;
3274 break;
3275 }
3276 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003277 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003278 applyVolume = true;
3279 }
3280 }
3281 if (isPreempted || applyVolume) {
3282 break;
3283 }
3284 }
3285 if (!applyVolume) {
3286 continue; // next output
3287 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003288 }
François Gaffieed91f582020-01-31 10:35:37 +01003289 //FIXME: workaround for truncated touch sounds
3290 // delayed volume change for system stream to be removed when the problem is
3291 // handled by system UI
3292 status_t volStatus = checkAndSetVolume(
3293 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003294 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003295 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3296 if (volStatus != NO_ERROR) {
3297 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003298 }
3299 }
François Gaffiecfe17322018-11-07 13:41:29 +01003300 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3301 return status;
3302}
3303
François Gaffieaaac0fd2018-11-22 17:56:39 +01003304status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003305 audio_devices_t device,
3306 IVolumeCurves &volumeCurves)
3307{
3308 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3309 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003310 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3311 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003312 (index > volumeCurves.getVolumeIndexMax())) {
3313 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3314 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3315 return BAD_VALUE;
3316 }
3317 if (!audio_is_output_device(device)) {
3318 return BAD_VALUE;
3319 }
3320
3321 // Force max volume if stream cannot be muted
3322 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3323
François Gaffieaaac0fd2018-11-22 17:56:39 +01003324 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003325 volumeCurves.addCurrentVolumeIndex(device, index);
3326 return NO_ERROR;
3327}
3328
3329status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3330 int &index,
3331 audio_devices_t device)
3332{
3333 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3334 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003335 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003336 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003337 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003338 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003339 }
jiabin9a3361e2019-10-01 09:38:30 -07003340 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003341}
3342
3343status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3344 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003345 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003346{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003347 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003348 return BAD_VALUE;
3349 }
jiabin9a3361e2019-10-01 09:38:30 -07003350 index = curves.getVolumeIndex(deviceTypes);
3351 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003352 return NO_ERROR;
3353}
3354
3355status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3356 int &index)
3357{
3358 index = getVolumeCurves(attr).getVolumeIndexMin();
3359 return NO_ERROR;
3360}
3361
3362status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3363 int &index)
3364{
3365 index = getVolumeCurves(attr).getVolumeIndexMax();
3366 return NO_ERROR;
3367}
3368
Eric Laurent36829f92017-04-07 19:04:42 -07003369audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003370{
3371 // select one output among several suitable for global effects.
3372 // The priority is as follows:
3373 // 1: An offloaded output. If the effect ends up not being offloadable,
3374 // AudioFlinger will invalidate the track and the offloaded output
3375 // will be closed causing the effect to be moved to a PCM output.
3376 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003377 // 3: The primary output
3378 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003379
François Gaffiec005e562018-11-06 15:04:49 +01003380 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3381 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003382 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003383
Eric Laurent36829f92017-04-07 19:04:42 -07003384 if (outputs.size() == 0) {
3385 return AUDIO_IO_HANDLE_NONE;
3386 }
Eric Laurente552edb2014-03-10 17:42:56 -07003387
Eric Laurent36829f92017-04-07 19:04:42 -07003388 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3389 bool activeOnly = true;
3390
3391 while (output == AUDIO_IO_HANDLE_NONE) {
3392 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3393 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3394 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3395
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003396 for (audio_io_handle_t output : outputs) {
3397 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003398 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003399 continue;
3400 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003401 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3402 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003403 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003404 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003405 }
3406 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003407 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003408 }
3409 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003410 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003411 }
3412 }
3413 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3414 output = outputOffloaded;
3415 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3416 output = outputDeepBuffer;
3417 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3418 output = outputPrimary;
3419 } else {
3420 output = outputs[0];
3421 }
3422 activeOnly = false;
3423 }
3424
3425 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003426 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003427 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3428 mMusicEffectOutput = output;
3429 }
3430
3431 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003432 return output;
3433}
3434
Eric Laurent36829f92017-04-07 19:04:42 -07003435audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3436{
3437 return selectOutputForMusicEffects();
3438}
3439
Eric Laurente0720872014-03-11 09:30:41 -07003440status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003441 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003442 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003443 int session,
3444 int id)
3445{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003446 if (session != AUDIO_SESSION_DEVICE) {
3447 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003448 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003449 index = mInputs.indexOfKey(io);
3450 if (index < 0) {
3451 ALOGW("registerEffect() unknown io %d", io);
3452 return INVALID_OPERATION;
3453 }
Eric Laurente552edb2014-03-10 17:42:56 -07003454 }
3455 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003456 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3457 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3458 || strategy == PRODUCT_STRATEGY_NONE));
3459 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003460}
3461
Eric Laurentc241b0d2018-11-28 09:08:49 -08003462status_t AudioPolicyManager::unregisterEffect(int id)
3463{
3464 if (mEffects.getEffect(id) == nullptr) {
3465 return INVALID_OPERATION;
3466 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003467 if (mEffects.isEffectEnabled(id)) {
3468 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3469 setEffectEnabled(id, false);
3470 }
3471 return mEffects.unregisterEffect(id);
3472}
3473
3474status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3475{
3476 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3477 if (effect == nullptr) {
3478 return INVALID_OPERATION;
3479 }
3480
3481 status_t status = mEffects.setEffectEnabled(id, enabled);
3482 if (status == NO_ERROR) {
3483 mInputs.trackEffectEnabled(effect, enabled);
3484 }
3485 return status;
3486}
3487
Eric Laurent6c796322019-04-09 14:13:17 -07003488
3489status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3490{
3491 mEffects.moveEffects(ids, io);
3492 return NO_ERROR;
3493}
3494
Eric Laurentc75307b2015-03-17 15:29:32 -07003495bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3496{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003497 auto vs = toVolumeSource(stream, false);
3498 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003499}
3500
3501bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3502{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003503 auto vs = toVolumeSource(stream, false);
3504 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003505}
3506
Eric Laurente0720872014-03-11 09:30:41 -07003507bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003508{
3509 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003510 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003511 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003512 return true;
3513 }
3514 }
3515 return false;
3516}
3517
Eric Laurent275e8e92014-11-30 15:14:47 -08003518// Register a list of custom mixes with their attributes and format.
3519// When a mix is registered, corresponding input and output profiles are
3520// added to the remote submix hw module. The profile contains only the
3521// parameters (sampling rate, format...) specified by the mix.
3522// The corresponding input remote submix device is also connected.
3523//
3524// When a remote submix device is connected, the address is checked to select the
3525// appropriate profile and the corresponding input or output stream is opened.
3526//
3527// When capture starts, getInputForAttr() will:
3528// - 1 look for a mix matching the address passed in attribtutes tags if any
3529// - 2 if none found, getDeviceForInputSource() will:
3530// - 2.1 look for a mix matching the attributes source
3531// - 2.2 if none found, default to device selection by policy rules
3532// At this time, the corresponding output remote submix device is also connected
3533// and active playback use cases can be transferred to this mix if needed when reconnecting
3534// after AudioTracks are invalidated
3535//
3536// When playback starts, getOutputForAttr() will:
3537// - 1 look for a mix matching the address passed in attribtutes tags if any
3538// - 2 if none found, look for a mix matching the attributes usage
3539// - 3 if none found, default to device and output selection by policy rules.
3540
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003541status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003542{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003543 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3544 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003545 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003546 sp<HwModule> rSubmixModule;
3547 // examine each mix's route type
3548 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003549 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003550 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3551 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3552 ALOGE("Unsupported Policy Mix %zu of %zu: "
3553 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3554 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003555 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003556 break;
3557 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003558 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3559 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003560 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003561 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3562 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003563 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003564 rSubmixModule = mHwModules.getModuleFromName(
3565 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3566 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003567 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003568 i);
3569 res = INVALID_OPERATION;
3570 break;
3571 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003572 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003573
Eric Laurent97ac8712018-07-27 18:59:02 -07003574 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003575 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003576 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003577 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003578 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3579 } else {
3580 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3581 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003582 }
François Gaffie036e1e92015-03-19 10:16:24 +01003583
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003584 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003585 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003586 res = INVALID_OPERATION;
3587 break;
3588 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003589 audio_config_t outputConfig = mix.mFormat;
3590 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003591 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3592 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003593 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3594 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003595 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003596 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003597 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003598 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003599
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003600 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003601 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3602 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3603 ALOGE("Failed to set remote submix device available, type %u, address %s",
3604 mix.mDeviceType, address.string());
3605 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003606 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003607 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3608 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003609 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003610 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003611 i, mixes.size(), type, address.string());
3612
3613 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3614 mix.mDeviceType, mix.mDeviceAddress,
3615 String8(), AUDIO_FORMAT_DEFAULT);
3616 if (device == nullptr) {
3617 res = INVALID_OPERATION;
3618 break;
3619 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003620
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003621 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003622 // First try to find an already opened output supporting the device
3623 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003624 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003625
Eric Laurentc529cf62020-04-17 18:19:10 -07003626 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003627 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003628 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3629 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003630 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003631 } else {
3632 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003633 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003634 }
3635 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003636 // If no output found, try to find a direct output profile supporting the device
3637 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3638 sp<HwModule> module = mHwModules[i];
3639 for (size_t j = 0;
3640 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3641 j++) {
3642 sp<IOProfile> profile = module->getOutputProfiles()[j];
3643 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3644 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3645 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3646 address.string());
3647 res = INVALID_OPERATION;
3648 } else {
3649 foundOutput = true;
3650 }
3651 }
3652 }
3653 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003654 if (res != NO_ERROR) {
3655 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003656 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003657 res = INVALID_OPERATION;
3658 break;
3659 } else if (!foundOutput) {
3660 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003661 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003662 res = INVALID_OPERATION;
3663 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003664 } else {
3665 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003666 }
Eric Laurentc722f302014-12-10 11:21:49 -08003667 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003668 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003669 if (res != NO_ERROR) {
3670 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003671 } else if (checkOutputs) {
3672 checkForDeviceAndOutputChanges();
3673 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003674 }
3675 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003676}
3677
3678status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3679{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003680 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003681 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003682 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003683 sp<HwModule> rSubmixModule;
3684 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003685 for (const auto& mix : mixes) {
3686 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003687
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003688 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003689 rSubmixModule = mHwModules.getModuleFromName(
3690 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3691 if (rSubmixModule == 0) {
3692 res = INVALID_OPERATION;
3693 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003694 }
3695 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003696
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003697 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003698
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003699 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003700 res = INVALID_OPERATION;
3701 continue;
3702 }
3703
Kevin Rocard04ed0462019-05-02 17:53:24 -07003704 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3705 if (getDeviceConnectionState(device, address.string()) ==
3706 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3707 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3708 address.string(), "remote-submix",
3709 AUDIO_FORMAT_DEFAULT);
3710 if (res != OK) {
3711 ALOGE("Error making RemoteSubmix device unavailable for mix "
3712 "with type %d, address %s", device, address.string());
3713 }
3714 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003715 }
jiabin5740f082019-08-19 15:08:30 -07003716 rSubmixModule->removeOutputProfile(address.c_str());
3717 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003718
Kevin Rocard153f92d2018-12-18 18:33:28 -08003719 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003720 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003721 res = INVALID_OPERATION;
3722 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003723 } else {
3724 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003725 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003726 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003727 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003728 if (res == NO_ERROR && checkOutputs) {
3729 checkForDeviceAndOutputChanges();
3730 updateCallAndOutputRouting();
3731 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003732 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003733}
3734
Mikhail Naganov100f0122018-11-29 11:22:16 -08003735void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3736{
3737 size_t i = 0;
3738 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3739 for (const auto& fmt : mManualSurroundFormats) {
3740 if (i++ != 0) dst->append(", ");
3741 std::string sfmt;
3742 FormatConverter::toString(fmt, sfmt);
3743 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3744 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3745 }
3746}
3747
Eric Laurentc529cf62020-04-17 18:19:10 -07003748// Returns true if all devices types match the predicate and are supported by one HW module
3749bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003750 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003751 std::function<bool(audio_devices_t)> predicate,
3752 const char *context) {
3753 for (size_t i = 0; i < devices.size(); i++) {
3754 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003755 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003756 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003757 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003758 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003759 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003760 return false;
3761 }
3762 }
3763 return true;
3764}
3765
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003766status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003767 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003768 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003769 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3770 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003771 }
3772 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003773 if (res != NO_ERROR) {
3774 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3775 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003776 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003777
3778 checkForDeviceAndOutputChanges();
3779 updateCallAndOutputRouting();
3780
3781 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003782}
3783
3784status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3785 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003786 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3787 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003788 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003789 __FUNCTION__, uid);
3790 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003791 }
3792
Eric Laurentc529cf62020-04-17 18:19:10 -07003793 checkForDeviceAndOutputChanges();
3794 updateCallAndOutputRouting();
3795
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003796 return res;
3797}
3798
Eric Laurent2517af32020-11-25 15:31:27 +01003799
jiabin0a488932020-08-07 17:32:40 -07003800status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3801 device_role_t role,
3802 const AudioDeviceTypeAddrVector &devices) {
3803 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3804 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003805
Eric Laurentc529cf62020-04-17 18:19:10 -07003806 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003807 return BAD_VALUE;
3808 }
jiabin0a488932020-08-07 17:32:40 -07003809 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003810 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003811 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3812 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003813 return status;
3814 }
3815
3816 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003817
3818 bool forceVolumeReeval = false;
3819 // FIXME: workaround for truncated touch sounds
3820 // to be removed when the problem is handled by system UI
3821 uint32_t delayMs = 0;
3822 if (strategy == mCommunnicationStrategy) {
3823 forceVolumeReeval = true;
3824 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3825 updateInputRouting();
3826 }
3827 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003828
3829 return NO_ERROR;
3830}
3831
3832void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3833{
3834 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003835 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003836 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003837 // Only apply special touch sound delay once
3838 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003839 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003840 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003841 for (size_t i = 0; i < mOutputs.size(); i++) {
3842 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3843 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003844 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3845 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003846 // As done in setDeviceConnectionState, we could also fix default device issue by
3847 // preventing the force re-routing in case of default dev that distinguishes on address.
3848 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003849 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003850 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3851 // If the device is using preferred mixer attributes, the output need to reopen
3852 // with default configuration when the new selected devices are different from
3853 // current routing devices.
3854 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3855 continue;
3856 }
Francois Gaffie601801d2021-06-22 13:27:39 +02003857 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3858 true /*requiresMuteCheck*/,
3859 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003860 // Only apply special touch sound delay once
3861 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003862 }
3863 if (forceVolumeReeval && !newDevices.isEmpty()) {
3864 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3865 }
3866 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003867 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01003868 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003869}
3870
Eric Laurent2517af32020-11-25 15:31:27 +01003871void AudioPolicyManager::updateInputRouting() {
3872 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303873 // Skip for hotword recording as the input device switch
3874 // is handled within sound trigger HAL
3875 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3876 continue;
3877 }
Eric Laurent2517af32020-11-25 15:31:27 +01003878 auto newDevice = getNewInputDevice(activeDesc);
3879 // Force new input selection if the new device can not be reached via current input
3880 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3881 setInputDevice(activeDesc->mIoHandle, newDevice);
3882 } else {
3883 closeInput(activeDesc->mIoHandle);
3884 }
3885 }
3886}
3887
Paul Wang5d7cdb52022-11-22 09:45:06 +00003888status_t
3889AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3890 device_role_t role,
3891 const AudioDeviceTypeAddrVector &devices) {
3892 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3893 dumpAudioDeviceTypeAddrVector(devices).c_str());
3894
3895 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3896 return BAD_VALUE;
3897 }
3898 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
3899 if (status != NO_ERROR) {
3900 ALOGW("Engine could not remove devices %s for strategy %d role %d",
3901 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
3902 return status;
3903 }
3904
3905 checkForDeviceAndOutputChanges();
3906
3907 bool forceVolumeReeval = false;
3908 // TODO(b/263479999): workaround for truncated touch sounds
3909 // to be removed when the problem is handled by system UI
3910 uint32_t delayMs = 0;
3911 if (strategy == mCommunnicationStrategy) {
3912 forceVolumeReeval = true;
3913 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3914 updateInputRouting();
3915 }
3916 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
3917
3918 return NO_ERROR;
3919}
3920
3921status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
3922 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003923{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003924 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003925
Paul Wang5d7cdb52022-11-22 09:45:06 +00003926 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003927 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01003928 ALOGW_IF(status != NAME_NOT_FOUND,
3929 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01003930 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003931 return status;
3932 }
3933
3934 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003935
3936 bool forceVolumeReeval = false;
3937 // FIXME: workaround for truncated touch sounds
3938 // to be removed when the problem is handled by system UI
3939 uint32_t delayMs = 0;
3940 if (strategy == mCommunnicationStrategy) {
3941 forceVolumeReeval = true;
3942 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3943 updateInputRouting();
3944 }
3945 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003946
3947 return NO_ERROR;
3948}
3949
jiabin0a488932020-08-07 17:32:40 -07003950status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3951 device_role_t role,
3952 AudioDeviceTypeAddrVector &devices) {
3953 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003954}
3955
Jiabin Huang3b98d322020-09-03 17:54:16 +00003956status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3957 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3958 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3959 dumpAudioDeviceTypeAddrVector(devices).c_str());
3960
Mikhail Naganov55773032020-10-01 15:08:13 -07003961 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003962 return BAD_VALUE;
3963 }
3964 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3965 ALOGW_IF(status != NO_ERROR,
3966 "Engine could not set preferred devices %s for audio source %d role %d",
3967 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3968
3969 return status;
3970}
3971
3972status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3973 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3974 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3975 dumpAudioDeviceTypeAddrVector(devices).c_str());
3976
Mikhail Naganov55773032020-10-01 15:08:13 -07003977 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003978 return BAD_VALUE;
3979 }
3980 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3981 ALOGW_IF(status != NO_ERROR,
3982 "Engine could not add preferred devices %s for audio source %d role %d",
3983 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3984
Eric Laurent2517af32020-11-25 15:31:27 +01003985 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003986 return status;
3987}
3988
3989status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3990 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3991{
3992 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3993 dumpAudioDeviceTypeAddrVector(devices).c_str());
3994
Mikhail Naganov55773032020-10-01 15:08:13 -07003995 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003996 return BAD_VALUE;
3997 }
3998
3999 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4000 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004001 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004002 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004003 if (status == NO_ERROR) {
4004 updateInputRouting();
4005 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004006 return status;
4007}
4008
4009status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4010 device_role_t role) {
4011 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4012
4013 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004014 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004015 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004016 if (status == NO_ERROR) {
4017 updateInputRouting();
4018 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004019 return status;
4020}
4021
4022status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4023 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4024 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4025}
4026
Oscar Azucena90e77632019-11-27 17:12:28 -08004027status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004028 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004029 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004030 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4031 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004032 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004033 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4034 if (status != NO_ERROR) {
4035 ALOGE("%s() could not set device affinity for userId %d",
4036 __FUNCTION__, userId);
4037 return status;
4038 }
4039
4040 // reevaluate outputs for all devices
4041 checkForDeviceAndOutputChanges();
4042 updateCallAndOutputRouting();
4043
4044 return NO_ERROR;
4045}
4046
4047status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004048 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08004049 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4050 if (status != NO_ERROR) {
4051 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4052 __FUNCTION__, userId);
4053 return status;
4054 }
4055
4056 // reevaluate outputs for all devices
4057 checkForDeviceAndOutputChanges();
4058 updateCallAndOutputRouting();
4059
4060 return NO_ERROR;
4061}
4062
Andy Hungc29d82b2018-10-05 12:23:17 -07004063void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004064{
Andy Hungc29d82b2018-10-05 12:23:17 -07004065 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004066 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004067 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004068 std::string stateLiteral;
4069 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004070 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004071 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4072 "communications", "media", "record", "dock", "system",
4073 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4074 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4075 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004076 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4077 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4078 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4079 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4080 dst->append(" (MANUAL: ");
4081 dumpManualSurroundFormats(dst);
4082 dst->append(")");
4083 }
4084 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004085 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004086 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4087 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004088 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07004089 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01004090
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004091 dst->append("\n");
4092 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4093 dst->append("\n");
4094 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004095 mHwModulesAll.dump(dst);
4096 mOutputs.dump(dst);
4097 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004098 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004099 mAudioPatches.dump(dst);
4100 mPolicyMixes.dump(dst);
4101 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004102
Kevin Rocardb99cc752019-03-21 20:52:24 -07004103 dst->appendFormat(" AllowedCapturePolicies:\n");
4104 for (auto& policy : mAllowedCapturePolicies) {
4105 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4106 }
4107
jiabina84c3d32022-12-02 18:59:55 +00004108 dst->appendFormat(" Preferred mixer audio configuration:\n");
4109 for (const auto it : mPreferredMixerAttrInfos) {
4110 dst->appendFormat(" - device port id: %d\n", it.first);
4111 for (const auto preferredMixerInfoIt : it.second) {
4112 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4113 preferredMixerInfoIt.second->dump(dst);
4114 }
4115 }
4116
François Gaffiec005e562018-11-06 15:04:49 +01004117 dst->appendFormat("\nPolicy Engine dump:\n");
4118 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004119}
4120
4121status_t AudioPolicyManager::dump(int fd)
4122{
4123 String8 result;
4124 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07004125 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004126 return NO_ERROR;
4127}
4128
Kevin Rocardb99cc752019-03-21 20:52:24 -07004129status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4130{
4131 mAllowedCapturePolicies[uid] = capturePolicy;
4132 return NO_ERROR;
4133}
4134
Eric Laurente552edb2014-03-10 17:42:56 -07004135// This function checks for the parameters which can be offloaded.
4136// This can be enhanced depending on the capability of the DSP and policy
4137// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004138audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004139{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004140 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004141 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004142 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004143 offloadInfo.format,
4144 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4145 offloadInfo.has_video);
4146
jiabin2b9d5a12021-12-10 01:06:29 +00004147 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004148 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004149 }
4150
4151 // See if there is a profile to support this.
4152 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004153 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004154 offloadInfo.sample_rate,
4155 offloadInfo.format,
4156 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004157 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4158 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004159 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4160 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4161 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004162 if (profile == nullptr) {
4163 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4164 }
4165 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4166 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4167 }
4168 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004169}
4170
Michael Chana94fbb22018-04-24 14:31:19 +10004171bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4172 const audio_attributes_t& attributes) {
4173 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004174 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004175 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4176 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004177 config.sample_rate,
4178 config.format,
4179 config.channel_mask,
4180 output_flags,
4181 true /* directOnly */);
4182 ALOGV("%s() profile %sfound with name: %s, "
4183 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4184 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004185 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004186 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004187
4188 // also try the MSD module if compatible profile not found
4189 if (profile == nullptr) {
4190 profile = getMsdProfileForOutput(outputDevices,
4191 config.sample_rate,
4192 config.format,
4193 config.channel_mask,
4194 output_flags,
4195 true /* directOnly */);
4196 ALOGV("%s() MSD profile %sfound with name: %s, "
4197 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4198 __FUNCTION__, profile != 0 ? "" : "NOT ",
4199 (profile != 0 ? profile->getTagName().c_str() : "null"),
4200 config.sample_rate, config.format, config.channel_mask, output_flags);
4201 }
4202 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004203}
4204
jiabin2b9d5a12021-12-10 01:06:29 +00004205bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4206 bool durationIgnored) {
4207 if (mMasterMono) {
4208 return false; // no offloading if mono is set.
4209 }
4210
4211 // Check if offload has been disabled
4212 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4213 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4214 return false;
4215 }
4216
4217 // Check if stream type is music, then only allow offload as of now.
4218 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4219 {
4220 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4221 return false;
4222 }
4223
4224 //TODO: enable audio offloading with video when ready
4225 const bool allowOffloadWithVideo =
4226 property_get_bool("audio.offload.video", false /* default_value */);
4227 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4228 ALOGV("%s: has_video == true, returning false", __func__);
4229 return false;
4230 }
4231
4232 //If duration is less than minimum value defined in property, return false
4233 const int min_duration_secs = property_get_int32(
4234 "audio.offload.min.duration.secs", -1 /* default_value */);
4235 if (!durationIgnored) {
4236 if (min_duration_secs >= 0) {
4237 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4238 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4239 __func__, min_duration_secs);
4240 return false;
4241 }
4242 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4243 ALOGV("%s: Offload denied by duration < default min(=%u)",
4244 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4245 return false;
4246 }
4247 }
4248
4249 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4250 // creating an offloaded track and tearing it down immediately after start when audioflinger
4251 // detects there is an active non offloadable effect.
4252 // FIXME: We should check the audio session here but we do not have it in this context.
4253 // This may prevent offloading in rare situations where effects are left active by apps
4254 // in the background.
4255 if (mEffects.isNonOffloadableEffectEnabled()) {
4256 return false;
4257 }
4258
4259 return true;
4260}
4261
4262audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4263 const audio_config_t *config) {
4264 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4265 offloadInfo.format = config->format;
4266 offloadInfo.sample_rate = config->sample_rate;
4267 offloadInfo.channel_mask = config->channel_mask;
4268 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4269 offloadInfo.has_video = false;
4270 offloadInfo.is_streaming = false;
4271 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4272
4273 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4274 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4275 audio_flags_to_audio_output_flags(attr->flags, &flags);
4276 // only retain flags that will drive compressed offload or passthrough
4277 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4278 if (offloadPossible) {
4279 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4280 }
4281 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4282
Dorin Drimusfae3c642022-03-17 18:36:30 +01004283 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004284 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004285 DeviceVector outputDevices = engineOutputDevices;
4286 // the MSD module checks for different conditions and output devices
4287 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4288 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4289 continue;
4290 }
4291 outputDevices = getMsdAudioOutDevices();
4292 }
jiabin2b9d5a12021-12-10 01:06:29 +00004293 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004294 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004295 config->sample_rate, nullptr /*updatedSamplingRate*/,
4296 config->format, nullptr /*updatedFormat*/,
4297 config->channel_mask, nullptr /*updatedChannelMask*/,
4298 flags)) {
4299 continue;
4300 }
4301 // reject profiles not corresponding to a device currently available
4302 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4303 continue;
4304 }
4305 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4306 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004307 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004308 != AUDIO_DIRECT_NOT_SUPPORTED) {
4309 // Already reports offload gapless supported. No need to report offload support.
4310 continue;
4311 }
4312 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4313 != AUDIO_OUTPUT_FLAG_NONE) {
4314 // If offload gapless is reported, no need to report offload support.
4315 directMode = (audio_direct_mode_t) ((directMode &
4316 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4317 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4318 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004319 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004320 }
4321 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004322 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004323 }
4324 }
4325 }
4326 return directMode;
4327}
4328
Dorin Drimusf2196d82022-01-03 12:11:18 +01004329status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4330 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004331 if (mEffects.isNonOffloadableEffectEnabled()) {
4332 return OK;
4333 }
jiabinf1c73972022-04-14 16:28:52 -07004334 DeviceVector devices;
4335 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004336 if (status != OK) {
4337 return status;
4338 }
4339 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4340 if (devices.empty()) {
4341 return OK; // no output devices for the attributes
4342 }
jiabinf1c73972022-04-14 16:28:52 -07004343 return getProfilesForDevices(devices, audioProfilesVector,
4344 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004345}
4346
jiabina84c3d32022-12-02 18:59:55 +00004347status_t AudioPolicyManager::getSupportedMixerAttributes(
4348 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4349 ALOGV("%s, portId=%d", __func__, portId);
4350 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4351 if (deviceDescriptor == nullptr) {
4352 ALOGE("%s the requested device is currently unavailable", __func__);
4353 return BAD_VALUE;
4354 }
4355 for (const auto& hwModule : mHwModules) {
4356 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4357 if (curProfile->supportsDevice(deviceDescriptor)) {
4358 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4359 }
4360 }
4361 }
4362 return NO_ERROR;
4363}
4364
4365status_t AudioPolicyManager::setPreferredMixerAttributes(
4366 const audio_attributes_t *attr,
4367 audio_port_handle_t portId,
4368 uid_t uid,
4369 const audio_mixer_attributes_t *mixerAttributes) {
4370 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4371 "mixerBehavior=%d}, uid=%d, portId=%u",
4372 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4373 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4374 mixerAttributes->mixer_behavior, uid, portId);
4375 if (attr->usage != AUDIO_USAGE_MEDIA) {
4376 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4377 return BAD_VALUE;
4378 }
4379 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4380 if (deviceDescriptor == nullptr) {
4381 ALOGE("%s the requested device is currently unavailable", __func__);
4382 return BAD_VALUE;
4383 }
4384 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4385 ALOGE("%s(%d), type=%d, is not a usb output device",
4386 __func__, portId, deviceDescriptor->type());
4387 return BAD_VALUE;
4388 }
4389
4390 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4391 audio_flags_to_audio_output_flags(attr->flags, &flags);
4392 flags = (audio_output_flags_t) (flags |
4393 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4394 sp<IOProfile> profile = nullptr;
4395 DeviceVector devices(deviceDescriptor);
4396 for (const auto& hwModule : mHwModules) {
4397 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4398 if (curProfile->hasDynamicAudioProfile()
4399 && curProfile->isCompatibleProfile(devices,
4400 mixerAttributes->config.sample_rate,
4401 nullptr /*updatedSamplingRate*/,
4402 mixerAttributes->config.format,
4403 nullptr /*updatedFormat*/,
4404 mixerAttributes->config.channel_mask,
4405 nullptr /*updatedChannelMask*/,
4406 flags,
4407 false /*exactMatchRequiredForInputFlags*/)) {
4408 profile = curProfile;
4409 break;
4410 }
4411 }
4412 }
4413 if (profile == nullptr) {
4414 ALOGE("%s, there is no compatible profile found", __func__);
4415 return BAD_VALUE;
4416 }
4417
4418 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4419 sp<PreferredMixerAttributesInfo>::make(
4420 uid, portId, profile, flags, *mixerAttributes);
4421 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4422 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4423
4424 // If 1) there is any client from the preferred mixer configuration owner that is currently
4425 // active and matches the strategy and 2) current output is on the preferred device and the
4426 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4427 // configuration.
4428 std::vector<audio_io_handle_t> outputsToReopen;
4429 for (size_t i = 0; i < mOutputs.size(); i++) {
4430 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004431 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4432 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4433 output->mUsePreferredMixerAttributes = true;
4434 } else {
4435 for (const auto &client: output->getActiveClients()) {
4436 if (client->uid() == uid && client->strategy() == strategy) {
4437 client->setIsInvalid();
4438 outputsToReopen.push_back(output->mIoHandle);
4439 }
jiabina84c3d32022-12-02 18:59:55 +00004440 }
4441 }
4442 }
4443 }
4444 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4445 config.sample_rate = mixerAttributes->config.sample_rate;
4446 config.channel_mask = mixerAttributes->config.channel_mask;
4447 config.format = mixerAttributes->config.format;
4448 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004449 sp<SwAudioOutputDescriptor> desc =
4450 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4451 if (desc == nullptr) {
4452 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4453 continue;
4454 }
4455 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004456 }
4457
4458 return NO_ERROR;
4459}
4460
4461sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
4462 audio_port_handle_t devicePortId, product_strategy_t strategy) {
4463 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4464 if (it == mPreferredMixerAttrInfos.end()) {
4465 return nullptr;
4466 }
4467 auto mixerAttrInfoIt = it->second.find(strategy);
4468 if (mixerAttrInfoIt == it->second.end()) {
4469 return nullptr;
4470 }
4471 return mixerAttrInfoIt->second;
4472}
4473
4474status_t AudioPolicyManager::getPreferredMixerAttributes(
4475 const audio_attributes_t *attr,
4476 audio_port_handle_t portId,
4477 audio_mixer_attributes_t* mixerAttributes) {
4478 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4479 portId, mEngine->getProductStrategyForAttributes(*attr));
4480 if (info == nullptr) {
4481 return NAME_NOT_FOUND;
4482 }
4483 *mixerAttributes = info->getMixerAttributes();
4484 return NO_ERROR;
4485}
4486
4487status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4488 audio_port_handle_t portId,
4489 uid_t uid) {
4490 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4491 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4492 if (preferredMixerAttrInfo == nullptr) {
4493 return NAME_NOT_FOUND;
4494 }
4495 if (preferredMixerAttrInfo->getUid() != uid) {
4496 ALOGE("%s, requested uid=%d, owned uid=%d",
4497 __func__, uid, preferredMixerAttrInfo->getUid());
4498 return PERMISSION_DENIED;
4499 }
4500 mPreferredMixerAttrInfos[portId].erase(strategy);
4501 if (mPreferredMixerAttrInfos[portId].empty()) {
4502 mPreferredMixerAttrInfos.erase(portId);
4503 }
4504
4505 // Reconfig existing output
4506 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4507 for (size_t i = 0; i < mOutputs.size(); i++) {
4508 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4509 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4510 }
4511 }
4512 for (const auto output : potentialOutputsToReopen) {
4513 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4514 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4515 preferredMixerAttrInfo->getFlags())) {
4516 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4517 }
4518 }
4519 return NO_ERROR;
4520}
4521
Eric Laurent6a94d692014-05-20 11:18:06 -07004522status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4523 audio_port_type_t type,
4524 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004525 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004526 unsigned int *generation)
4527{
jiabin19cdba52020-11-24 11:28:58 -08004528 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4529 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004530 return BAD_VALUE;
4531 }
4532 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004533 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004534 *num_ports = 0;
4535 }
4536
4537 size_t portsWritten = 0;
4538 size_t portsMax = *num_ports;
4539 *num_ports = 0;
4540 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004541 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4542 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004543 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004544 for (const auto& dev : mAvailableOutputDevices) {
4545 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004546 continue;
4547 }
4548 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004549 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004550 }
4551 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004552 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004553 }
4554 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004555 for (const auto& dev : mAvailableInputDevices) {
4556 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004557 continue;
4558 }
4559 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004560 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004561 }
4562 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004563 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004564 }
4565 }
4566 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4567 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4568 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4569 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4570 }
4571 *num_ports += mInputs.size();
4572 }
4573 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004574 size_t numOutputs = 0;
4575 for (size_t i = 0; i < mOutputs.size(); i++) {
4576 if (!mOutputs[i]->isDuplicated()) {
4577 numOutputs++;
4578 if (portsWritten < portsMax) {
4579 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4580 }
4581 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004582 }
Eric Laurent84c70242014-06-23 08:46:27 -07004583 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004584 }
4585 }
jiabina84c3d32022-12-02 18:59:55 +00004586
Eric Laurent6a94d692014-05-20 11:18:06 -07004587 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004588 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004589 return NO_ERROR;
4590}
4591
jiabin19cdba52020-11-24 11:28:58 -08004592status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004593{
Eric Laurent99fcae42018-05-17 16:59:18 -07004594 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4595 return BAD_VALUE;
4596 }
4597 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4598 if (dev != 0) {
4599 dev->toAudioPort(port);
4600 return NO_ERROR;
4601 }
4602 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4603 if (dev != 0) {
4604 dev->toAudioPort(port);
4605 return NO_ERROR;
4606 }
4607 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4608 if (out != 0) {
4609 out->toAudioPort(port);
4610 return NO_ERROR;
4611 }
4612 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4613 if (in != 0) {
4614 in->toAudioPort(port);
4615 return NO_ERROR;
4616 }
4617 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004618}
4619
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004620status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4621 audio_patch_handle_t *handle,
4622 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004623{
François Gaffieafd4cea2019-11-18 15:50:22 +01004624 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004625 if (handle == NULL || patch == NULL) {
4626 return BAD_VALUE;
4627 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004628 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004629 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004630 return BAD_VALUE;
4631 }
4632 // only one source per audio patch supported for now
4633 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004634 return INVALID_OPERATION;
4635 }
Eric Laurent874c42872014-08-08 15:13:39 -07004636 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004637 return INVALID_OPERATION;
4638 }
Eric Laurent874c42872014-08-08 15:13:39 -07004639 for (size_t i = 0; i < patch->num_sinks; i++) {
4640 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4641 return INVALID_OPERATION;
4642 }
4643 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004644
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004645 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4646 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4647 if (srcDevice == nullptr || sinkDevice == nullptr) {
4648 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4649 return BAD_VALUE;
4650 }
4651 ALOGV("%s between source %s and sink %s", __func__,
4652 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4653 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4654 // Default attributes, default volume priority, not to infer with non raw audio patches.
4655 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4656 const struct audio_port_config *source = &patch->sources[0];
4657 sp<SourceClientDescriptor> sourceDesc =
4658 new InternalSourceClientDescriptor(
4659 portId, uid, attributes, *source, srcDevice, sinkDevice,
4660 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4661
4662 status_t status =
4663 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4664
4665 if (status != NO_ERROR) {
4666 return INVALID_OPERATION;
4667 }
4668 mAudioSources.add(portId, sourceDesc);
4669 return NO_ERROR;
4670}
4671
4672status_t AudioPolicyManager::connectAudioSourceToSink(
4673 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4674 const struct audio_patch *patch,
4675 audio_patch_handle_t &handle,
4676 uid_t uid, uint32_t delayMs)
4677{
4678 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4679 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4680 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4681 return INVALID_OPERATION;
4682 }
4683 sourceDesc->connect(handle, sinkDevice);
4684 if (isMsdPatch(handle)) {
4685 return NO_ERROR;
4686 }
4687 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4688 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4689 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4690 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4691 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4692 goto FailurePatchAdded;
4693 }
4694 status = swOutput->start();
4695 if (status != NO_ERROR) {
4696 goto FailureSourceAdded;
4697 }
4698 swOutput->addClient(sourceDesc);
4699 status = startSource(swOutput, sourceDesc, &delayMs);
4700 if (status != NO_ERROR) {
4701 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4702 goto FailureSourceActive;
4703 }
4704 if (delayMs != 0) {
4705 usleep(delayMs * 1000);
4706 }
4707 return NO_ERROR;
4708
4709FailureSourceActive:
4710 swOutput->stop();
4711 releaseOutput(sourceDesc->portId());
4712FailureSourceAdded:
4713 sourceDesc->setSwOutput(nullptr);
4714FailurePatchAdded:
4715 releaseAudioPatchInternal(handle);
4716 return INVALID_OPERATION;
4717}
4718
4719status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4720 audio_patch_handle_t *handle,
4721 uid_t uid, uint32_t delayMs,
4722 const sp<SourceClientDescriptor>& sourceDesc)
4723{
4724 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004725 sp<AudioPatch> patchDesc;
4726 ssize_t index = mAudioPatches.indexOfKey(*handle);
4727
François Gaffieafd4cea2019-11-18 15:50:22 +01004728 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4729 patch->sources[0].role,
4730 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004731#if LOG_NDEBUG == 0
4732 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004733 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4734 patch->sinks[i].role,
4735 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004736 }
4737#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004738
4739 if (index >= 0) {
4740 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004741 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4742 __func__, mUidCached, patchDesc->getUid(), uid);
4743 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004744 return INVALID_OPERATION;
4745 }
4746 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004747 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004748 }
4749
4750 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004751 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004752 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004753 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004754 return BAD_VALUE;
4755 }
Eric Laurent84c70242014-06-23 08:46:27 -07004756 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4757 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004758 if (patchDesc != 0) {
4759 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004760 ALOGV("%s source id differs for patch current id %d new id %d",
4761 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004762 return BAD_VALUE;
4763 }
4764 }
Eric Laurent874c42872014-08-08 15:13:39 -07004765 DeviceVector devices;
4766 for (size_t i = 0; i < patch->num_sinks; i++) {
4767 // Only support mix to devices connection
4768 // TODO add support for mix to mix connection
4769 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004770 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004771 return INVALID_OPERATION;
4772 }
4773 sp<DeviceDescriptor> devDesc =
4774 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4775 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004776 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004777 return BAD_VALUE;
4778 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004779
François Gaffie11d30102018-11-02 16:09:09 +01004780 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004781 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004782 NULL, // updatedSamplingRate
4783 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004784 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004785 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004786 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004787 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004788 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004789 return INVALID_OPERATION;
4790 }
4791 devices.add(devDesc);
4792 }
4793 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004794 return INVALID_OPERATION;
4795 }
Eric Laurent874c42872014-08-08 15:13:39 -07004796
Eric Laurent6a94d692014-05-20 11:18:06 -07004797 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004798 ALOGV("%s setting device %s on output %d",
4799 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004800 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004801 index = mAudioPatches.indexOfKey(*handle);
4802 if (index >= 0) {
4803 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004804 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004805 }
4806 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004807 patchDesc->setUid(uid);
4808 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004809 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004810 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004811 return INVALID_OPERATION;
4812 }
4813 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4814 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4815 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004816 // only one sink supported when connecting an input device to a mix
4817 if (patch->num_sinks > 1) {
4818 return INVALID_OPERATION;
4819 }
François Gaffie53615e22015-03-19 09:24:12 +01004820 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004821 if (inputDesc == NULL) {
4822 return BAD_VALUE;
4823 }
4824 if (patchDesc != 0) {
4825 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4826 return BAD_VALUE;
4827 }
4828 }
François Gaffie11d30102018-11-02 16:09:09 +01004829 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004830 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004831 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004832 return BAD_VALUE;
4833 }
4834
François Gaffie11d30102018-11-02 16:09:09 +01004835 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004836 patch->sinks[0].sample_rate,
4837 NULL, /*updatedSampleRate*/
4838 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004839 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004840 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004841 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004842 // FIXME for the parameter type,
4843 // and the NONE
4844 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004845 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004846 return INVALID_OPERATION;
4847 }
4848 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004849 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004850 device->toString().c_str(), inputDesc->mIoHandle);
4851 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004852 index = mAudioPatches.indexOfKey(*handle);
4853 if (index >= 0) {
4854 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004855 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004856 }
4857 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004858 patchDesc->setUid(uid);
4859 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004860 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004861 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004862 return INVALID_OPERATION;
4863 }
4864 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4865 // device to device connection
4866 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004867 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004868 return BAD_VALUE;
4869 }
4870 }
François Gaffie11d30102018-11-02 16:09:09 +01004871 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004872 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004873 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004874 return BAD_VALUE;
4875 }
Eric Laurent874c42872014-08-08 15:13:39 -07004876
Eric Laurent6a94d692014-05-20 11:18:06 -07004877 //update source and sink with our own data as the data passed in the patch may
4878 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004879 PatchBuilder patchBuilder;
4880 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004881
4882 // if first sink is to MSD, establish single MSD patch
4883 if (getMsdAudioOutDevices().contains(
4884 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4885 ALOGV("%s patching to MSD", __FUNCTION__);
4886 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4887 goto installPatch;
4888 }
4889
François Gaffieafd4cea2019-11-18 15:50:22 +01004890 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4891 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004892
Eric Laurent874c42872014-08-08 15:13:39 -07004893 for (size_t i = 0; i < patch->num_sinks; i++) {
4894 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004895 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004896 return INVALID_OPERATION;
4897 }
François Gaffie11d30102018-11-02 16:09:09 +01004898 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004899 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004900 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004901 return BAD_VALUE;
4902 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004903 audio_port_config sinkPortConfig = {};
4904 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4905 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004906
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004907 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4908 // volume management purpose (tracking activity)
4909 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4910 // in config XML to reach the sink so that is can be declared as available.
4911 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004912 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004913 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004914 // take care of dynamic routing for SwOutput selection,
4915 audio_attributes_t attributes = sourceDesc->attributes();
4916 audio_stream_type_t stream = sourceDesc->stream();
4917 audio_attributes_t resultAttr;
4918 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4919 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02004920 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
4921 config.channel_mask =
4922 (audio_channel_mask_get_representation(sourceMask)
4923 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
4924 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004925 config.format = sourceDesc->config().format;
4926 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4927 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4928 bool isRequestedDeviceForExclusiveUse = false;
4929 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004930 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00004931 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004932 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4933 &stream, sourceDesc->uid(), &config, &flags,
4934 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00004935 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004936 if (output == AUDIO_IO_HANDLE_NONE) {
4937 ALOGV("%s no output for device %s",
4938 __FUNCTION__, sinkDevice->toString().c_str());
4939 return INVALID_OPERATION;
4940 }
4941 outputDesc = mOutputs.valueFor(output);
4942 if (outputDesc->isDuplicated()) {
4943 ALOGE("%s output is duplicated", __func__);
4944 return INVALID_OPERATION;
4945 }
François Gaffie7e39df22022-04-26 12:48:49 +02004946 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4947 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004948 } else {
4949 // Same for "raw patches" aka created from createAudioPatch API
4950 SortedVector<audio_io_handle_t> outputs =
4951 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4952 // if the sink device is reachable via an opened output stream, request to
4953 // go via this output stream by adding a second source to the patch
4954 // description
4955 output = selectOutput(outputs);
4956 if (output == AUDIO_IO_HANDLE_NONE) {
4957 ALOGE("%s no output available for internal patch sink", __func__);
4958 return INVALID_OPERATION;
4959 }
4960 outputDesc = mOutputs.valueFor(output);
4961 if (outputDesc->isDuplicated()) {
4962 ALOGV("%s output for device %s is duplicated",
4963 __func__, sinkDevice->toString().c_str());
4964 return INVALID_OPERATION;
4965 }
François Gaffie7e39df22022-04-26 12:48:49 +02004966 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004967 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004968 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004969 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004970 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004971 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004972 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4973 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004974 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4975 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004976 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004977 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004978 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004979 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004980 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004981 return INVALID_OPERATION;
4982 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004983 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004984 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004985 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004986 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004987 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02004988 srcMixPortConfig.ext.mix.usecase.stream =
4989 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004990 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4991 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004992 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004993 }
Eric Laurent83b88082014-06-20 18:31:16 -07004994 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004995 }
4996 // TODO: check from routing capabilities in config file and other conflicting patches
4997
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004998installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004999 status_t status = installPatch(
5000 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005001 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005002 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005003 return INVALID_OPERATION;
5004 }
5005 } else {
5006 return BAD_VALUE;
5007 }
5008 } else {
5009 return BAD_VALUE;
5010 }
5011 return NO_ERROR;
5012}
5013
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005014status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005015{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005016 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005017 ssize_t index = mAudioPatches.indexOfKey(handle);
5018
5019 if (index < 0) {
5020 return BAD_VALUE;
5021 }
5022 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005023 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5024 __func__, mUidCached, patchDesc->getUid(), uid);
5025 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005026 return INVALID_OPERATION;
5027 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005028 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5029 for (size_t i = 0; i < mAudioSources.size(); i++) {
5030 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5031 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5032 portId = sourceDesc->portId();
5033 break;
5034 }
5035 }
5036 return portId != AUDIO_PORT_HANDLE_NONE ?
5037 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005038}
Eric Laurent6a94d692014-05-20 11:18:06 -07005039
François Gaffieafd4cea2019-11-18 15:50:22 +01005040status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005041 uint32_t delayMs,
5042 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005043{
5044 ALOGV("%s patch %d", __func__, handle);
5045 if (mAudioPatches.indexOfKey(handle) < 0) {
5046 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5047 return BAD_VALUE;
5048 }
5049 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005050 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005051 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005052 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005053 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005054 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005055 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005056 return BAD_VALUE;
5057 }
5058
François Gaffie11d30102018-11-02 16:09:09 +01005059 setOutputDevices(outputDesc,
5060 getNewOutputDevices(outputDesc, true /*fromCache*/),
5061 true,
5062 0,
5063 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005064 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5065 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005066 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005067 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005068 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005069 return BAD_VALUE;
5070 }
5071 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005072 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005073 true,
5074 NULL);
5075 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005076 status_t status =
5077 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5078 ALOGV("%s patch panel returned %d patchHandle %d",
5079 __func__, status, patchDesc->getAfHandle());
5080 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005081 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005082 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005083 // SW or HW Bridge
5084 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5085 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005086 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005087 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5088 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5089 outputDesc = sourceDesc->swOutput().promote();
5090 }
5091 if (outputDesc == nullptr) {
5092 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5093 // releaseOutput has already called closeOutput in case of direct output
5094 return NO_ERROR;
5095 }
François Gaffie7e39df22022-04-26 12:48:49 +02005096 patchHandle = outputDesc->getPatchHandle();
5097 // When a Sw bridge is released, the mixer used by this bridge will release its
5098 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
5099 // Reuse patch handle to force audio flinger removing initial mixer patch removal
5100 // updating hal patch handle (prevent leaks).
5101 // While using a HwBridge, force reconsidering device only if not reusing an existing
5102 // output and no more activity on output (will force to close).
5103 bool force = sourceDesc->useSwBridge() ||
5104 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
5105 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5106 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5107 // Reconsider device only for cases:
5108 // 1 / Active Output
5109 // 2 / Inactive Output previously hosting HwBridge
5110 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5111 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5112 sourceDesc->canCloseOutput();
5113 setOutputDevices(outputDesc,
5114 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5115 outputDesc->devices(),
5116 force,
5117 0,
5118 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005119 } else {
5120 return BAD_VALUE;
5121 }
5122 } else {
5123 return BAD_VALUE;
5124 }
5125 return NO_ERROR;
5126}
5127
5128status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5129 struct audio_patch *patches,
5130 unsigned int *generation)
5131{
François Gaffie53615e22015-03-19 09:24:12 +01005132 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005133 return BAD_VALUE;
5134 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005135 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005136 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005137}
5138
Eric Laurente1715a42014-05-20 11:30:42 -07005139status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005140{
Eric Laurente1715a42014-05-20 11:30:42 -07005141 ALOGV("setAudioPortConfig()");
5142
5143 if (config == NULL) {
5144 return BAD_VALUE;
5145 }
5146 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5147 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005148 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5149 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005150 }
5151
Eric Laurenta121f902014-06-03 13:32:54 -07005152 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005153 if (config->type == AUDIO_PORT_TYPE_MIX) {
5154 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005155 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005156 if (outputDesc == NULL) {
5157 return BAD_VALUE;
5158 }
Eric Laurent84c70242014-06-23 08:46:27 -07005159 ALOG_ASSERT(!outputDesc->isDuplicated(),
5160 "setAudioPortConfig() called on duplicated output %d",
5161 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005162 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005163 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005164 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005165 if (inputDesc == NULL) {
5166 return BAD_VALUE;
5167 }
Eric Laurenta121f902014-06-03 13:32:54 -07005168 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005169 } else {
5170 return BAD_VALUE;
5171 }
5172 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5173 sp<DeviceDescriptor> deviceDesc;
5174 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5175 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5176 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5177 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5178 } else {
5179 return BAD_VALUE;
5180 }
5181 if (deviceDesc == NULL) {
5182 return BAD_VALUE;
5183 }
Eric Laurenta121f902014-06-03 13:32:54 -07005184 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005185 } else {
5186 return BAD_VALUE;
5187 }
5188
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005189 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005190 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5191 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005192 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005193 audioPortConfig->toAudioPortConfig(&newConfig, config);
5194 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005195 }
Eric Laurenta121f902014-06-03 13:32:54 -07005196 if (status != NO_ERROR) {
5197 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005198 }
Eric Laurente1715a42014-05-20 11:30:42 -07005199
5200 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005201}
5202
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005203void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5204{
Eric Laurentd60560a2015-04-10 11:31:20 -07005205 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005206 clearAudioPatches(uid);
5207 clearSessionRoutes(uid);
5208}
5209
Eric Laurent6a94d692014-05-20 11:18:06 -07005210void AudioPolicyManager::clearAudioPatches(uid_t uid)
5211{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005212 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005213 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005214 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005215 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005216 }
5217 }
5218}
5219
François Gaffiec005e562018-11-06 15:04:49 +01005220void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005221{
François Gaffiec005e562018-11-06 15:04:49 +01005222 // Take the first attributes following the product strategy as it is used to retrieve the routed
5223 // device. All attributes wihin a strategy follows the same "routing strategy"
5224 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5225 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005226 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005227 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005228 for (size_t j = 0; j < mOutputs.size(); j++) {
5229 if (mOutputs.keyAt(j) == ouptutToSkip) {
5230 continue;
5231 }
5232 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005233 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005234 continue;
5235 }
5236 // If the default device for this strategy is on another output mix,
5237 // invalidate all tracks in this strategy to force re connection.
5238 // Otherwise select new device on the output mix.
5239 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005240 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005241 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005242 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5243 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5244 // If the device is using preferred mixer attributes, the output need to reopen
5245 // with default configuration when the new selected devices are different from
5246 // current routing devices.
5247 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5248 continue;
5249 }
5250 setOutputDevices(outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005251 }
5252 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005253 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005254}
5255
5256void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5257{
5258 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005259 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005260 for (size_t i = 0; i < mOutputs.size(); i++) {
5261 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005262 for (const auto& client : outputDesc->getClientIterable()) {
5263 if (client->hasPreferredDevice() && client->uid() == uid) {
5264 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005265 auto clientStrategy = client->strategy();
5266 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5267 end(affectedStrategies)) {
5268 continue;
5269 }
5270 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005271 }
5272 }
5273 }
5274 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005275 for (const auto& strategy : affectedStrategies) {
5276 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005277 }
5278
5279 // remove input routes associated with this uid
5280 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005281 for (size_t i = 0; i < mInputs.size(); i++) {
5282 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005283 for (const auto& client : inputDesc->getClientIterable()) {
5284 if (client->hasPreferredDevice() && client->uid() == uid) {
5285 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5286 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005287 }
5288 }
5289 }
5290 // reroute inputs if necessary
5291 SortedVector<audio_io_handle_t> inputsToClose;
5292 for (size_t i = 0; i < mInputs.size(); i++) {
5293 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005294 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005295 inputsToClose.add(inputDesc->mIoHandle);
5296 }
5297 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005298 for (const auto& input : inputsToClose) {
5299 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005300 }
5301}
5302
Eric Laurentd60560a2015-04-10 11:31:20 -07005303void AudioPolicyManager::clearAudioSources(uid_t uid)
5304{
5305 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005306 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5307 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005308 stopAudioSource(mAudioSources.keyAt(i));
5309 }
5310 }
5311}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005312
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005313status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5314 audio_io_handle_t *ioHandle,
5315 audio_devices_t *device)
5316{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005317 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5318 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005319 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01005320 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005321
François Gaffiedf372692015-03-19 10:43:27 +01005322 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005323}
5324
Eric Laurentd60560a2015-04-10 11:31:20 -07005325status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005326 const audio_attributes_t *attributes,
5327 audio_port_handle_t *portId,
5328 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005329{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005330 ALOGV("%s", __FUNCTION__);
5331 *portId = AUDIO_PORT_HANDLE_NONE;
5332
5333 if (source == NULL || attributes == NULL || portId == NULL) {
5334 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5335 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005336 return BAD_VALUE;
5337 }
5338
Eric Laurentd60560a2015-04-10 11:31:20 -07005339 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5340 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005341 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5342 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005343 return INVALID_OPERATION;
5344 }
5345
François Gaffie11d30102018-11-02 16:09:09 +01005346 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005347 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005348 String8(source->ext.device.address),
5349 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005350 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005351 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005352 return BAD_VALUE;
5353 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005354
jiabin4ef93452019-09-10 14:29:54 -07005355 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005356
François Gaffieaaac0fd2018-11-22 17:56:39 +01005357 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005358 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005359 mEngine->getStreamTypeForAttributes(*attributes),
5360 mEngine->getProductStrategyForAttributes(*attributes),
5361 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005362
5363 status_t status = connectAudioSource(sourceDesc);
5364 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005365 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005366 }
5367 return status;
5368}
5369
Francois Gaffie601801d2021-06-22 13:27:39 +02005370sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5371 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5372{
5373 ALOGV("%s", __FUNCTION__);
5374 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5375
5376 status_t status = startAudioSource(source, attributes, &portId, uid);
5377 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5378 return mAudioSources.valueFor(portId);
5379}
5380
5381
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005382status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005383{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005384 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005385
5386 // make sure we only have one patch per source.
5387 disconnectAudioSource(sourceDesc);
5388
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005389 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005390 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5391 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5392 sourceDesc->srcDevice()->type(),
5393 String8(sourceDesc->srcDevice()->address().c_str()),
5394 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005395 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005396 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005397 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005398 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005399 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5400 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5401 return INVALID_OPERATION;
5402 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005403 PatchBuilder patchBuilder;
5404 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5405 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005406
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005407 return connectAudioSourceToSink(
5408 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005409}
5410
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005411status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005412{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005413 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5414 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005415 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005416 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005417 return BAD_VALUE;
5418 }
5419 status_t status = disconnectAudioSource(sourceDesc);
5420
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005421 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005422 return status;
5423}
5424
Andy Hung2ddee192015-12-18 17:34:44 -08005425status_t AudioPolicyManager::setMasterMono(bool mono)
5426{
5427 if (mMasterMono == mono) {
5428 return NO_ERROR;
5429 }
5430 mMasterMono = mono;
5431 // if enabling mono we close all offloaded devices, which will invalidate the
5432 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5433 // for recreating the new AudioTrack as non-offloaded PCM.
5434 //
5435 // If disabling mono, we leave all tracks as is: we don't know which clients
5436 // and tracks are able to be recreated as offloaded. The next "song" should
5437 // play back offloaded.
5438 if (mMasterMono) {
5439 Vector<audio_io_handle_t> offloaded;
5440 for (size_t i = 0; i < mOutputs.size(); ++i) {
5441 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5442 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5443 offloaded.push(desc->mIoHandle);
5444 }
5445 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005446 for (const auto& handle : offloaded) {
5447 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005448 }
5449 }
5450 // update master mono for all remaining outputs
5451 for (size_t i = 0; i < mOutputs.size(); ++i) {
5452 updateMono(mOutputs.keyAt(i));
5453 }
5454 return NO_ERROR;
5455}
5456
5457status_t AudioPolicyManager::getMasterMono(bool *mono)
5458{
5459 *mono = mMasterMono;
5460 return NO_ERROR;
5461}
5462
Eric Laurentac9cef52017-06-09 15:46:26 -07005463float AudioPolicyManager::getStreamVolumeDB(
5464 audio_stream_type_t stream, int index, audio_devices_t device)
5465{
jiabin9a3361e2019-10-01 09:38:30 -07005466 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005467}
5468
jiabin81772902018-04-02 17:52:27 -07005469status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5470 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005471 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005472{
Kriti Dang6537def2021-03-02 13:46:59 +01005473 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5474 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005475 return BAD_VALUE;
5476 }
Kriti Dang6537def2021-03-02 13:46:59 +01005477 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5478 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005479
5480 size_t formatsWritten = 0;
5481 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005482
Kriti Dang6537def2021-03-02 13:46:59 +01005483 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005484 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5485 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005486 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005487 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005488 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005489 bool formatEnabled = true;
5490 switch (forceUse) {
5491 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005492 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005493 break;
5494 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5495 formatEnabled = false;
5496 break;
5497 default: // AUTO or ALWAYS => true
5498 break;
jiabin81772902018-04-02 17:52:27 -07005499 }
5500 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5501 }
jiabin81772902018-04-02 17:52:27 -07005502 }
5503 return NO_ERROR;
5504}
5505
Kriti Dang6537def2021-03-02 13:46:59 +01005506status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5507 audio_format_t *surroundFormats) {
5508 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5509 return BAD_VALUE;
5510 }
5511 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5512 __func__, *numSurroundFormats, surroundFormats);
5513
5514 size_t formatsWritten = 0;
5515 size_t formatsMax = *numSurroundFormats;
5516 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5517
5518 // Return formats from all device profiles that have already been resolved by
5519 // checkOutputsForDevice().
5520 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5521 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5522 audio_devices_t deviceType = device->type();
5523 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5524 // returns formats reported by HDMI devices.
5525 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5526 continue;
5527 }
5528 // Formats reported by sink devices
5529 std::unordered_set<audio_format_t> formatset;
5530 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5531 formatset.insert(it->second.begin(), it->second.end());
5532 }
5533
5534 // Formats hard-coded in the in policy configuration file (if any).
5535 FormatVector encodedFormats = device->encodedFormats();
5536 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5537 // Filter the formats which are supported by the vendor hardware.
5538 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5539 if (mConfig.getSurroundFormats().count(*it) != 0) {
5540 formats.insert(*it);
5541 } else {
5542 for (const auto& pair : mConfig.getSurroundFormats()) {
5543 if (pair.second.count(*it) != 0) {
5544 formats.insert(pair.first);
5545 break;
5546 }
5547 }
5548 }
5549 }
5550 }
5551 *numSurroundFormats = formats.size();
5552 for (const auto& format: formats) {
5553 if (formatsWritten < formatsMax) {
5554 surroundFormats[formatsWritten++] = format;
5555 }
5556 }
5557 return NO_ERROR;
5558}
5559
jiabin81772902018-04-02 17:52:27 -07005560status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5561{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005562 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005563 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5564 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005565 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005566 return BAD_VALUE;
5567 }
5568
Mikhail Naganov100f0122018-11-29 11:22:16 -08005569 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5570 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005571 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005572 return INVALID_OPERATION;
5573 }
5574
Mikhail Naganov100f0122018-11-29 11:22:16 -08005575 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005576 return NO_ERROR;
5577 }
5578
Mikhail Naganov100f0122018-11-29 11:22:16 -08005579 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005580 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005581 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005582 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005583 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005584 }
5585 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005586 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005587 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005588 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005589 }
5590 }
5591
5592 sp<SwAudioOutputDescriptor> outputDesc;
5593 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005594 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5595 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005596 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5597 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005598 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005599 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005600 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5601 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5602 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005603 name.c_str(),
5604 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005605 if (status != NO_ERROR) {
5606 continue;
5607 }
5608 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5609 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5610 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005611 name.c_str(),
5612 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005613 profileUpdated |= (status == NO_ERROR);
5614 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005615 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005616 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005617 AUDIO_DEVICE_IN_HDMI);
5618 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5619 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005620 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005621 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005622 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5623 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5624 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005625 name.c_str(),
5626 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005627 if (status != NO_ERROR) {
5628 continue;
5629 }
5630 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5631 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5632 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005633 name.c_str(),
5634 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005635 profileUpdated |= (status == NO_ERROR);
5636 }
5637
jiabin81772902018-04-02 17:52:27 -07005638 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005639 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005640 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005641 }
5642
5643 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5644}
5645
Eric Laurent5ada82e2019-08-29 17:53:54 -07005646void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005647{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005648 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005649 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005650 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005651 }
5652}
5653
jiabin6012f912018-11-02 17:06:30 -07005654bool AudioPolicyManager::isHapticPlaybackSupported()
5655{
5656 for (const auto& hwModule : mHwModules) {
5657 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5658 for (const auto &outProfile : outputProfiles) {
5659 struct audio_port audioPort;
5660 outProfile->toAudioPort(&audioPort);
5661 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5662 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5663 return true;
5664 }
5665 }
5666 }
5667 }
5668 return false;
5669}
5670
Carter Hsu325a8eb2022-01-19 19:56:51 +08005671bool AudioPolicyManager::isUltrasoundSupported()
5672{
5673 bool hasUltrasoundOutput = false;
5674 bool hasUltrasoundInput = false;
5675 for (const auto& hwModule : mHwModules) {
5676 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5677 if (!hasUltrasoundOutput) {
5678 for (const auto &outProfile : outputProfiles) {
5679 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5680 hasUltrasoundOutput = true;
5681 break;
5682 }
5683 }
5684 }
5685
5686 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5687 if (!hasUltrasoundInput) {
5688 for (const auto &inputProfile : inputProfiles) {
5689 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5690 hasUltrasoundInput = true;
5691 break;
5692 }
5693 }
5694 }
5695
5696 if (hasUltrasoundOutput && hasUltrasoundInput)
5697 return true;
5698 }
5699 return false;
5700}
5701
Atneya Nair698f5ef2022-12-15 16:15:09 -08005702bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5703{
5704 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5705 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5706 for (const auto& hwModule : mHwModules) {
5707 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5708 for (const auto &inputProfile : inputProfiles) {
5709 if ((inputProfile->getFlags() & mask) == mask) {
5710 return true;
5711 }
5712 }
5713 }
5714 return false;
5715}
5716
Eric Laurent8340e672019-11-06 11:01:08 -08005717bool AudioPolicyManager::isCallScreenModeSupported()
5718{
5719 return getConfig().isCallScreenModeSupported();
5720}
5721
5722
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005723status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005724{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005725 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005726 if (!sourceDesc->isConnected()) {
5727 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5728 return NO_ERROR;
5729 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005730 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5731 if (swOutput != 0) {
5732 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005733 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005734 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005735 }
jiabinbce0c1d2020-10-05 11:20:18 -07005736 if (releaseOutput(sourceDesc->portId())) {
5737 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5738 // no need to release audio patch here but just return NO_ERROR.
5739 return NO_ERROR;
5740 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005741 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005742 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005743 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005744 // close Hwoutput and remove from mHwOutputs
5745 } else {
5746 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5747 }
5748 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005749 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005750 sourceDesc->disconnect();
5751 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005752}
5753
François Gaffiec005e562018-11-06 15:04:49 +01005754sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5755 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005756{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005757 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005758 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005759 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005760 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005761 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5762 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005763 source = sourceDesc;
5764 break;
5765 }
5766 }
5767 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005768}
5769
Eric Laurentb4f42a92022-01-17 17:37:31 +01005770bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005771 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005772 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005773{
5774 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5775 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005776 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005777 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005778 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5779 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5780 return false;
5781 }
5782 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5783 return false;
5784 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005785 }
5786
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005787 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005788 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005789 if (profile == nullptr) {
5790 return false;
5791 }
5792
5793 // The caller can have the audio config criteria ignored by either passing a null ptr or
5794 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005795 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005796 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005797
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005798 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005799 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005800 return false;
5801 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005802 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005803 return true;
5804}
5805
5806void AudioPolicyManager::checkVirtualizerClientRoutes() {
5807 std::set<audio_stream_type_t> streamsToInvalidate;
5808 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005809 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5810 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005811 audio_attributes_t attr = client->attributes();
5812 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5813 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5814 audio_config_base_t clientConfig = client->config();
5815 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005816 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005817 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005818 streamsToInvalidate.insert(client->stream());
5819 }
5820 }
5821 }
5822
jiabinc44b3462022-12-08 12:52:31 -08005823 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005824}
5825
Eric Laurente191d1b2022-04-15 11:59:25 +02005826
5827bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5828 const sp<SwAudioOutputDescriptor>& outputDesc) {
5829 if (outputDesc->isDuplicated()) {
5830 return false;
5831 }
5832 DeviceVector devices = outputDesc->supportedDevices();
5833 for (size_t i = 0; i < mOutputs.size(); i++) {
5834 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5835 if (desc == outputDesc || desc->isDuplicated()) {
5836 continue;
5837 }
5838 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5839 if (!sharedDevices.isEmpty()
5840 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5841 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5842 return false;
5843 }
5844 }
5845 return true;
5846}
5847
5848
Eric Laurentfa0f6742021-08-17 18:39:44 +02005849status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005850 const audio_attributes_t *attr,
5851 audio_io_handle_t *output) {
5852 *output = AUDIO_IO_HANDLE_NONE;
5853
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005854 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5855 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5856 audio_config_t *configPtr = nullptr;
5857 audio_config_t config;
5858 if (mixerConfig != nullptr) {
5859 config = audio_config_initializer(mixerConfig);
5860 configPtr = &config;
5861 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005862 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005863 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005864 return BAD_VALUE;
5865 }
5866
5867 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005868 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005869 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005870 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005871 return BAD_VALUE;
5872 }
5873
Eric Laurente191d1b2022-04-15 11:59:25 +02005874 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005875 for (size_t i = 0; i < mOutputs.size(); i++) {
5876 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005877 if (!desc->isDuplicated()
5878 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5879 spatializerOutputs.push_back(desc);
5880 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005881 }
5882 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005883 mSpatializerOutput.clear();
5884 bool outputsChanged = false;
5885 for (const auto& desc : spatializerOutputs) {
5886 if (desc->mProfile == profile
5887 && (configPtr == nullptr
5888 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5889 mSpatializerOutput = desc;
5890 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5891 } else {
5892 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5893 " and devices %s", __func__, desc->mIoHandle,
5894 configPtr != nullptr ? configPtr->channel_mask : 0,
5895 devices.toString().c_str());
5896 closeOutput(desc->mIoHandle);
5897 outputsChanged = true;
5898 }
Eric Laurent39095982021-08-24 18:29:27 +02005899 }
5900
Eric Laurente191d1b2022-04-15 11:59:25 +02005901 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005902 sp<SwAudioOutputDescriptor> desc =
5903 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005904 if (desc != nullptr) {
5905 mSpatializerOutput = desc;
5906 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005907 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005908 }
5909
5910 checkVirtualizerClientRoutes();
5911
Eric Laurente191d1b2022-04-15 11:59:25 +02005912 if (outputsChanged) {
5913 mPreviousOutputs = mOutputs;
5914 mpClientInterface->onAudioPortListUpdate();
5915 }
5916
5917 if (mSpatializerOutput == nullptr) {
5918 ALOGV("%s could not open spatializer output with requested config", __func__);
5919 return BAD_VALUE;
5920 }
Eric Laurent39095982021-08-24 18:29:27 +02005921 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005922 ALOGV("%s returning new spatializer output %d", __func__, *output);
5923 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005924}
5925
Eric Laurentfa0f6742021-08-17 18:39:44 +02005926status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5927 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005928 return INVALID_OPERATION;
5929 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005930 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005931 return BAD_VALUE;
5932 }
Eric Laurent39095982021-08-24 18:29:27 +02005933
Eric Laurente191d1b2022-04-15 11:59:25 +02005934 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5935 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5936 closeOutput(mSpatializerOutput->mIoHandle);
5937 //from now on mSpatializerOutput is null
5938 checkVirtualizerClientRoutes();
5939 }
Eric Laurent39095982021-08-24 18:29:27 +02005940
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005941 return NO_ERROR;
5942}
5943
Eric Laurente552edb2014-03-10 17:42:56 -07005944// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005945// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005946// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005947uint32_t AudioPolicyManager::nextAudioPortGeneration()
5948{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005949 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005950}
5951
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005952static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005953 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5954 !audioPolicyXmlConfigFile.empty()) {
5955 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5956 if (ret == NO_ERROR) {
5957 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005958 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005959 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005960 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005961 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005962}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005963
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005964AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5965 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005966 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005967 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005968 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005969 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005970 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005971 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005972 mAudioPortGeneration(1),
5973 mBeaconMuteRefCount(0),
5974 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005975 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005976 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005977 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005978 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005979{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005980}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005981
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005982AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5983 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5984{
5985 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005986}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005987
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005988void AudioPolicyManager::loadConfig() {
5989 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005990 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005991 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005992 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005993}
5994
5995status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005996 {
5997 auto engLib = EngineLibrary::load(
5998 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5999 if (!engLib) {
6000 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
6001 return NO_INIT;
6002 }
6003 mEngine = engLib->createEngine();
6004 if (mEngine == nullptr) {
6005 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
6006 return NO_INIT;
6007 }
François Gaffie2110e042015-03-24 08:41:51 +01006008 }
6009 mEngine->setObserver(this);
6010 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006011 if (status != NO_ERROR) {
6012 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6013 return status;
6014 }
François Gaffie2110e042015-03-24 08:41:51 +01006015
Mikhail Naganove93ae282023-02-02 15:28:26 -08006016 // If microphones address is empty, set it according to device type
6017 for (size_t i = 0; i < mInputDevicesAll.size(); i++) {
6018 if (mInputDevicesAll[i]->address().empty()) {
6019 if (mInputDevicesAll[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
6020 mInputDevicesAll[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
6021 } else if (mInputDevicesAll[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
6022 mInputDevicesAll[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
6023 }
6024 }
6025 }
6026
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006027 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006028 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6029 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6030
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006031 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006032 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006033 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006034
Eric Laurent3a4311c2014-03-17 12:00:47 -07006035 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01006036 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
6037 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
6038 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006039 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006040 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006041 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006042
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006043 // Silence ALOGV statements
6044 property_set("log.tag." LOG_TAG, "D");
6045
Eric Laurente552edb2014-03-10 17:42:56 -07006046 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006047 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006048}
6049
Eric Laurente0720872014-03-11 09:30:41 -07006050AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006051{
Eric Laurente552edb2014-03-10 17:42:56 -07006052 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006053 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006054 }
6055 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006056 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006057 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006058 mAvailableOutputDevices.clear();
6059 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006060 mOutputs.clear();
6061 mInputs.clear();
6062 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08006063 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006064 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006065}
6066
Eric Laurente0720872014-03-11 09:30:41 -07006067status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006068{
Eric Laurent87ffa392015-05-22 10:32:38 -07006069 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006070}
6071
Eric Laurente552edb2014-03-10 17:42:56 -07006072// ---
6073
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006074void AudioPolicyManager::onNewAudioModulesAvailable()
6075{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006076 DeviceVector newDevices;
6077 onNewAudioModulesAvailableInt(&newDevices);
6078 if (!newDevices.empty()) {
6079 nextAudioPortGeneration();
6080 mpClientInterface->onAudioPortListUpdate();
6081 }
6082}
6083
6084void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6085{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006086 for (const auto& hwModule : mHwModulesAll) {
6087 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6088 continue;
6089 }
6090 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
6091 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
6092 ALOGW("could not open HW module %s", hwModule->getName());
6093 continue;
6094 }
6095 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006096 // open all output streams needed to access attached devices.
6097 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006098 // This also validates mAvailableOutputDevices list
6099 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6100 if (!outProfile->canOpenNewIo()) {
6101 ALOGE("Invalid Output profile max open count %u for profile %s",
6102 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6103 continue;
6104 }
6105 if (!outProfile->hasSupportedDevices()) {
6106 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6107 continue;
6108 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006109 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6110 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006111 mTtsOutputAvailable = true;
6112 }
6113
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006114 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
6115 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
6116 sp<DeviceDescriptor> supportedDevice = 0;
6117 if (supportedDevices.contains(mDefaultOutputDevice)) {
6118 supportedDevice = mDefaultOutputDevice;
6119 } else {
6120 // choose first device present in profile's SupportedDevices also part of
6121 // mAvailableOutputDevices.
6122 if (availProfileDevices.isEmpty()) {
6123 continue;
6124 }
6125 supportedDevice = availProfileDevices.itemAt(0);
6126 }
6127 if (!mOutputDevicesAll.contains(supportedDevice)) {
6128 continue;
6129 }
6130 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6131 mpClientInterface);
6132 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006133 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6134 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006135 AUDIO_STREAM_DEFAULT,
6136 AUDIO_OUTPUT_FLAG_NONE, &output);
6137 if (status != NO_ERROR) {
6138 ALOGW("Cannot open output stream for devices %s on hw module %s",
6139 supportedDevice->toString().c_str(), hwModule->getName());
6140 continue;
6141 }
6142 for (const auto &device : availProfileDevices) {
6143 // give a valid ID to an attached device once confirmed it is reachable
6144 if (!device->isAttached()) {
6145 device->attach(hwModule);
6146 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006147 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006148 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006149 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6150 }
6151 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006152 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006153 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6154 mPrimaryOutput = outputDesc;
6155 }
Eric Laurent39095982021-08-24 18:29:27 +02006156 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006157 outputDesc->close();
6158 } else {
6159 addOutput(output, outputDesc);
6160 setOutputDevices(outputDesc,
6161 DeviceVector(supportedDevice),
6162 true,
6163 0,
6164 NULL);
6165 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006166 }
6167 // open input streams needed to access attached devices to validate
6168 // mAvailableInputDevices list
6169 for (const auto& inProfile : hwModule->getInputProfiles()) {
6170 if (!inProfile->canOpenNewIo()) {
6171 ALOGE("Invalid Input profile max open count %u for profile %s",
6172 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6173 continue;
6174 }
6175 if (!inProfile->hasSupportedDevices()) {
6176 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6177 continue;
6178 }
6179 // chose first device present in profile's SupportedDevices also part of
6180 // available input devices
6181 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
6182 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
6183 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006184 ALOGV("%s: Input device list is empty! for profile %s",
6185 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006186 continue;
6187 }
6188 sp<AudioInputDescriptor> inputDesc =
6189 new AudioInputDescriptor(inProfile, mpClientInterface);
6190
6191 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6192 status_t status = inputDesc->open(nullptr,
6193 availProfileDevices.itemAt(0),
6194 AUDIO_SOURCE_MIC,
6195 AUDIO_INPUT_FLAG_NONE,
6196 &input);
6197 if (status != NO_ERROR) {
6198 ALOGW("Cannot open input stream for device %s on hw module %s",
6199 availProfileDevices.toString().c_str(),
6200 hwModule->getName());
6201 continue;
6202 }
6203 for (const auto &device : availProfileDevices) {
6204 // give a valid ID to an attached device once confirmed it is reachable
6205 if (!device->isAttached()) {
6206 device->attach(hwModule);
6207 device->importAudioPortAndPickAudioProfile(inProfile, true);
6208 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006209 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006210 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6211 }
6212 }
6213 inputDesc->close();
6214 }
6215 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006216
6217 // Check if spatializer outputs can be closed until used.
6218 // mOutputs vector never contains duplicated outputs at this point.
6219 std::vector<audio_io_handle_t> outputsClosed;
6220 for (size_t i = 0; i < mOutputs.size(); i++) {
6221 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6222 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6223 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6224 outputsClosed.push_back(desc->mIoHandle);
6225 desc->close();
6226 }
6227 }
6228 for (auto output : outputsClosed) {
6229 removeOutput(output);
6230 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006231}
6232
Eric Laurent98e38192018-02-15 18:31:53 -08006233void AudioPolicyManager::addOutput(audio_io_handle_t output,
6234 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006235{
Eric Laurent1c333e22014-05-20 10:48:17 -07006236 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006237 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006238 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006239 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006240 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006241}
6242
François Gaffie53615e22015-03-19 09:24:12 +01006243void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6244{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006245 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6246 ALOGV("%s: removing primary output", __func__);
6247 mPrimaryOutput = nullptr;
6248 }
François Gaffie53615e22015-03-19 09:24:12 +01006249 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006250 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006251}
6252
Eric Laurent98e38192018-02-15 18:31:53 -08006253void AudioPolicyManager::addInput(audio_io_handle_t input,
6254 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006255{
Eric Laurent1c333e22014-05-20 10:48:17 -07006256 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006257 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006258}
Eric Laurente552edb2014-03-10 17:42:56 -07006259
François Gaffie11d30102018-11-02 16:09:09 +01006260status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006261 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006262 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006263{
François Gaffie11d30102018-11-02 16:09:09 +01006264 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006265 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006266 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006267
François Gaffie11d30102018-11-02 16:09:09 +01006268 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006269 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006270 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006271 }
Eric Laurente552edb2014-03-10 17:42:56 -07006272
Eric Laurent3b73df72014-03-11 09:06:29 -07006273 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006274 // first call getAudioPort to get the supported attributes from the HAL
6275 struct audio_port_v7 port = {};
6276 device->toAudioPort(&port);
6277 status_t status = mpClientInterface->getAudioPort(&port);
6278 if (status == NO_ERROR) {
6279 device->importAudioPort(port);
6280 }
6281
6282 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006283 for (size_t i = 0; i < mOutputs.size(); i++) {
6284 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006285 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006286 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006287 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6288 mOutputs.keyAt(i), device->toString().c_str());
6289 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006290 }
6291 }
6292 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006293 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006294 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006295 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6296 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006297 if (profile->supportsDevice(device)) {
6298 profiles.add(profile);
6299 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6300 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006301 }
6302 }
6303 }
6304
Eric Laurent7b279bb2015-12-14 10:18:23 -08006305 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006306
Eric Laurente552edb2014-03-10 17:42:56 -07006307 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006308 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006309 return BAD_VALUE;
6310 }
6311
6312 // open outputs for matching profiles if needed. Direct outputs are also opened to
6313 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6314 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006315 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006316
6317 // nothing to do if one output is already opened for this profile
6318 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006319 for (j = 0; j < outputs.size(); j++) {
6320 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006321 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006322 // matching profile: save the sample rates, format and channel masks supported
6323 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006324 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006325 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006326 }
Eric Laurente552edb2014-03-10 17:42:56 -07006327 break;
6328 }
6329 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006330 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006331 continue;
6332 }
6333
Eric Laurent3974e3b2017-12-07 17:58:43 -08006334 if (!profile->canOpenNewIo()) {
6335 ALOGW("Max Output number %u already opened for this profile %s",
6336 profile->maxOpenCount, profile->getTagName().c_str());
6337 continue;
6338 }
6339
Eric Laurent83efe1c2017-07-09 16:51:08 -07006340 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07006341 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006342 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6343 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006344 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006345 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006346 profiles.removeAt(profile_index);
6347 profile_index--;
6348 } else {
6349 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006350 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006351 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006352 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6353 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006354 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006355 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006356
François Gaffie11d30102018-11-02 16:09:09 +01006357 if (device_distinguishes_on_address(deviceType)) {
6358 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6359 device->toString().c_str());
6360 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
6361 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006362 }
Eric Laurente552edb2014-03-10 17:42:56 -07006363 ALOGV("checkOutputsForDevice(): adding output %d", output);
6364 }
6365 }
6366
6367 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006368 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006369 return BAD_VALUE;
6370 }
Eric Laurentd4692962014-05-05 18:13:44 -07006371 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006372 // check if one opened output is not needed any more after disconnecting one device
6373 for (size_t i = 0; i < mOutputs.size(); i++) {
6374 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006375 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006376 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006377 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006378 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006379 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006380 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006381 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6382 mOutputs.keyAt(i));
6383 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006384 }
Eric Laurente552edb2014-03-10 17:42:56 -07006385 }
6386 }
Eric Laurentd4692962014-05-05 18:13:44 -07006387 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006388 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006389 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6390 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006391 if (!profile->supportsDevice(device)) {
6392 continue;
6393 }
6394 ALOGV("checkOutputsForDevice(): "
6395 "clearing direct output profile %zu on module %s",
6396 j, hwModule->getName());
6397 profile->clearAudioProfiles();
6398 if (!profile->hasDynamicAudioProfile()) {
6399 continue;
6400 }
6401 // When a device is disconnected, if there is an IOProfile that contains dynamic
6402 // profiles and supports the disconnected device, call getAudioPort to repopulate
6403 // the capabilities of the devices that is supported by the IOProfile.
6404 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6405 if (supportedDevice == device ||
6406 !mAvailableOutputDevices.contains(supportedDevice)) {
6407 continue;
6408 }
6409 struct audio_port_v7 port;
6410 supportedDevice->toAudioPort(&port);
6411 status_t status = mpClientInterface->getAudioPort(&port);
6412 if (status == NO_ERROR) {
6413 supportedDevice->importAudioPort(port);
6414 }
Eric Laurente552edb2014-03-10 17:42:56 -07006415 }
6416 }
6417 }
6418 }
6419 return NO_ERROR;
6420}
6421
François Gaffie11d30102018-11-02 16:09:09 +01006422status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006423 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006424{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006425 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006426
François Gaffie11d30102018-11-02 16:09:09 +01006427 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006428 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006429 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006430 }
6431
Eric Laurentd4692962014-05-05 18:13:44 -07006432 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006433 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006434 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006435 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006436 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006437 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006438 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006439 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006440
François Gaffie11d30102018-11-02 16:09:09 +01006441 if (profile->supportsDevice(device)) {
6442 profiles.add(profile);
6443 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6444 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006445 }
6446 }
6447 }
6448
Eric Laurent0dd51852019-04-19 18:18:58 -07006449 if (profiles.isEmpty()) {
6450 ALOGW("%s: No input profile available for device %s",
6451 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006452 return BAD_VALUE;
6453 }
6454
6455 // open inputs for matching profiles if needed. Direct inputs are also opened to
6456 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6457 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6458
Eric Laurent1c333e22014-05-20 10:48:17 -07006459 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006460
Eric Laurentd4692962014-05-05 18:13:44 -07006461 // nothing to do if one input is already opened for this profile
6462 size_t input_index;
6463 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6464 desc = mInputs.valueAt(input_index);
6465 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006466 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006467 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006468 }
Eric Laurentd4692962014-05-05 18:13:44 -07006469 break;
6470 }
6471 }
6472 if (input_index != mInputs.size()) {
6473 continue;
6474 }
6475
Eric Laurent3974e3b2017-12-07 17:58:43 -08006476 if (!profile->canOpenNewIo()) {
6477 ALOGW("Max Input number %u already opened for this profile %s",
6478 profile->maxOpenCount, profile->getTagName().c_str());
6479 continue;
6480 }
6481
Eric Laurentfe231122017-11-17 17:48:06 -08006482 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006483 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006484 status_t status = desc->open(nullptr,
6485 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006486 AUDIO_SOURCE_MIC,
6487 AUDIO_INPUT_FLAG_NONE,
6488 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006489
Eric Laurentcf2c0212014-07-25 16:20:43 -07006490 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006491 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006492 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006493 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006494 mpClientInterface->setParameters(input, String8(param));
6495 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006496 }
François Gaffie11d30102018-11-02 16:09:09 +01006497 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006498 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006499 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006500 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006501 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006502 }
6503
Eric Laurent0dd51852019-04-19 18:18:58 -07006504 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006505 addInput(input, desc);
6506 }
6507 } // endif input != 0
6508
Eric Laurentcf2c0212014-07-25 16:20:43 -07006509 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006510 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006511 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006512 profiles.removeAt(profile_index);
6513 profile_index--;
6514 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006515 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006516 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006517 }
Eric Laurentd4692962014-05-05 18:13:44 -07006518 ALOGV("checkInputsForDevice(): adding input %d", input);
6519 }
6520 } // end scan profiles
6521
6522 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006523 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006524 return BAD_VALUE;
6525 }
6526 } else {
6527 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006528 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006529 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006530 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006531 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006532 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006533 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006534 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006535 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6536 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006537 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006538 }
6539 }
6540 }
6541 } // end disconnect
6542
6543 return NO_ERROR;
6544}
6545
6546
Eric Laurente0720872014-03-11 09:30:41 -07006547void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006548{
6549 ALOGV("closeOutput(%d)", output);
6550
François Gaffie1c878552018-11-22 16:53:21 +01006551 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6552 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006553 ALOGW("closeOutput() unknown output %d", output);
6554 return;
6555 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006556 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006557 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006558
Eric Laurente552edb2014-03-10 17:42:56 -07006559 // look for duplicated outputs connected to the output being removed.
6560 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006561 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6562 if (dupOutput->isDuplicated() &&
6563 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6564 sp<SwAudioOutputDescriptor> remainingOutput =
6565 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006566 // As all active tracks on duplicated output will be deleted,
6567 // and as they were also referenced on the other output, the reference
6568 // count for their stream type must be adjusted accordingly on
6569 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006570 const bool wasActive = remainingOutput->isActive();
6571 // Note: no-op on the closing output where all clients has already been set inactive
6572 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006573 // stop() will be a no op if the output is still active but is needed in case all
6574 // active streams refcounts where cleared above
6575 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006576 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006577 }
Eric Laurente552edb2014-03-10 17:42:56 -07006578 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6579 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6580
6581 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006582 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006583 }
6584 }
6585
Eric Laurent05b90f82014-08-27 15:32:29 -07006586 nextAudioPortGeneration();
6587
François Gaffie1c878552018-11-22 16:53:21 +01006588 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006589 if (index >= 0) {
6590 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006591 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6592 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006593 mAudioPatches.removeItemsAt(index);
6594 mpClientInterface->onAudioPatchListUpdate();
6595 }
6596
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006597 if (closingOutputWasActive) {
6598 closingOutput->stop();
6599 }
François Gaffie1c878552018-11-22 16:53:21 +01006600 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006601
François Gaffie53615e22015-03-19 09:24:12 +01006602 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006603 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006604 if (closingOutput == mSpatializerOutput) {
6605 mSpatializerOutput.clear();
6606 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006607
6608 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6609 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006610 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006611 bool directOutputOpen = false;
6612 for (size_t i = 0; i < mOutputs.size(); i++) {
6613 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6614 directOutputOpen = true;
6615 break;
6616 }
6617 }
6618 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006619 ALOGV("no direct outputs open, reset MSD patches");
6620 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6621 // how output devices for patching are resolved. Avoid by caching and reusing the
6622 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6623 // devices to patch to. This may be complicated by the fact that devices may become
6624 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006625 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006626 }
6627 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006628}
6629
6630void AudioPolicyManager::closeInput(audio_io_handle_t input)
6631{
6632 ALOGV("closeInput(%d)", input);
6633
6634 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6635 if (inputDesc == NULL) {
6636 ALOGW("closeInput() unknown input %d", input);
6637 return;
6638 }
6639
Eric Laurent6a94d692014-05-20 11:18:06 -07006640 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006641
François Gaffie11d30102018-11-02 16:09:09 +01006642 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006643 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006644 if (index >= 0) {
6645 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006646 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6647 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006648 mAudioPatches.removeItemsAt(index);
6649 mpClientInterface->onAudioPatchListUpdate();
6650 }
6651
Eric Laurentfe231122017-11-17 17:48:06 -08006652 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006653 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006654
François Gaffie11d30102018-11-02 16:09:09 +01006655 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6656 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006657 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006658 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006659 }
Eric Laurente552edb2014-03-10 17:42:56 -07006660}
6661
François Gaffie11d30102018-11-02 16:09:09 +01006662SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6663 const DeviceVector &devices,
6664 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006665{
6666 SortedVector<audio_io_handle_t> outputs;
6667
François Gaffie11d30102018-11-02 16:09:09 +01006668 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006669 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006670 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006671 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006672 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006673 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006674 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006675 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006676 outputs.add(openOutputs.keyAt(i));
6677 }
6678 }
6679 return outputs;
6680}
6681
Mikhail Naganov37977152018-07-11 15:54:44 -07006682void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6683{
6684 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6685 // output is suspended before any tracks are moved to it
6686 checkA2dpSuspend();
6687 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006688 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006689 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006690 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006691 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006692 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6693 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6694 // configuration changes will ultimately be rerouted correctly. We can still avoid
6695 // unnecessary rerouting by caching and reusing the arguments to
6696 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6697 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006698 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006699 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006700 // an event that changed routing likely occurred, inform upper layers
6701 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006702}
6703
François Gaffiec005e562018-11-06 15:04:49 +01006704bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6705 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006706{
François Gaffiec005e562018-11-06 15:04:49 +01006707 return mEngine->getProductStrategyForAttributes(lAttr) ==
6708 mEngine->getProductStrategyForAttributes(rAttr);
6709}
6710
Francois Gaffieff1eb522020-05-06 18:37:04 +02006711void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6712{
6713 for (size_t i = 0; i < mAudioSources.size(); i++) {
6714 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6715 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006716 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006717 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006718 connectAudioSource(sourceDesc);
6719 }
6720 }
6721}
6722
6723void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6724{
6725 for (size_t i = 0; i < mAudioSources.size(); i++) {
6726 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6727 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6728 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6729 disconnectAudioSource(sourceDesc);
6730 }
6731 }
6732}
6733
François Gaffiec005e562018-11-06 15:04:49 +01006734void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6735{
6736 auto psId = mEngine->getProductStrategyForAttributes(attr);
6737
6738 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6739 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006740
François Gaffie11d30102018-11-02 16:09:09 +01006741 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6742 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006743
Eric Laurentc209fe42020-06-05 18:11:23 -07006744 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006745 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006746 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006747 // take into account dynamic audio policies related changes: if a client is now associated
6748 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006749 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006750 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6751 if (desc->isDuplicated()) {
6752 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006753 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006754 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6755 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6756 continue;
6757 }
6758 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006759 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006760 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6761 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6762 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006763 if (status != OK) {
6764 continue;
6765 }
yucliuf4de36d2020-09-14 14:57:56 -07006766 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006767 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006768 maxLatency = desc->latency();
6769 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006770 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006771 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006772 }
6773 }
6774
Eric Laurent56ed8842022-11-15 16:04:41 +01006775 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006776 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6777 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006778 for (audio_io_handle_t srcOut : srcOutputs) {
6779 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006780 if (desc == nullptr) continue;
6781
6782 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006783 maxLatency = desc->latency();
6784 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006785
Eric Laurent56ed8842022-11-15 16:04:41 +01006786 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006787 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006788 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006789 // a client on a non direct outputs has necessarily a linear PCM format
6790 // so we can call selectOutput() safely
6791 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6792 client->flags(),
6793 client->config().format,
6794 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006795 client->config().sample_rate,
6796 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006797 if (newOutput != srcOut) {
6798 invalidate = true;
6799 break;
6800 }
6801 } else {
6802 sp<IOProfile> profile = getProfileForOutput(newDevices,
6803 client->config().sample_rate,
6804 client->config().format,
6805 client->config().channel_mask,
6806 client->flags(),
6807 true /* directOnly */);
6808 if (profile != desc->mProfile) {
6809 invalidate = true;
6810 break;
6811 }
6812 }
6813 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006814 // mute strategy while moving tracks from one output to another
6815 if (invalidate) {
6816 invalidatedOutputs.push_back(desc);
6817 if (desc->isStrategyActive(psId)) {
6818 setStrategyMute(psId, true, desc);
6819 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6820 newDevices.types());
6821 }
Eric Laurente552edb2014-03-10 17:42:56 -07006822 }
François Gaffiec005e562018-11-06 15:04:49 +01006823 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006824 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006825 connectAudioSource(source);
6826 }
Eric Laurente552edb2014-03-10 17:42:56 -07006827 }
6828
Eric Laurent56ed8842022-11-15 16:04:41 +01006829 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6830 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6831 std::to_string(srcOutputs[0]).c_str(),
6832 std::to_string(dstOutputs[0]).c_str());
6833
François Gaffiec005e562018-11-06 15:04:49 +01006834 // Move effects associated to this stream from previous output to new output
6835 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006836 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006837 }
François Gaffiec005e562018-11-06 15:04:49 +01006838 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006839 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006840 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006841 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006842 desc->setTracksInvalidatedStatusByStrategy(psId);
6843 }
Eric Laurente552edb2014-03-10 17:42:56 -07006844 }
6845 }
6846}
6847
Eric Laurente0720872014-03-11 09:30:41 -07006848void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006849{
François Gaffiec005e562018-11-06 15:04:49 +01006850 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6851 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6852 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006853 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006854 }
Eric Laurente552edb2014-03-10 17:42:56 -07006855}
6856
Kevin Rocard153f92d2018-12-18 18:33:28 -08006857void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08006858 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006859 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006860 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006861 for (size_t i = 0; i < mOutputs.size(); i++) {
6862 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6863 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006864 sp<AudioPolicyMix> primaryMix;
6865 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006866 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006867 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6868 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
6869 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006870 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6871 for (auto &secondaryMix : secondaryMixes) {
6872 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6873 if (outputDesc != nullptr &&
6874 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6875 secondaryDescs.push_back(outputDesc);
6876 }
6877 }
6878
jiabinc44b3462022-12-08 12:52:31 -08006879 if (status != OK &&
6880 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
6881 // When it failed to query secondary output, only invalidate the client that is not
6882 // MMAP. The reason is that MMAP stream will not support secondary output.
6883 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00006884 } else if (!std::equal(
6885 client->getSecondaryOutputs().begin(),
6886 client->getSecondaryOutputs().end(),
6887 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006888 if (!audio_is_linear_pcm(client->config().format)) {
6889 // If the format is not PCM, the tracks should be invalidated to get correct
6890 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08006891 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00006892 } else {
6893 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6894 std::vector<audio_io_handle_t> secondaryOutputIds;
6895 for (const auto &secondaryDesc: secondaryDescs) {
6896 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6897 weakSecondaryDescs.push_back(secondaryDesc);
6898 }
6899 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6900 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006901 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006902 }
6903 }
6904 }
jiabin10a03f12021-05-07 23:46:28 +00006905 if (!trackSecondaryOutputs.empty()) {
6906 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6907 }
jiabinc44b3462022-12-08 12:52:31 -08006908 if (!clientsToInvalidate.empty()) {
6909 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
6910 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006911 }
6912}
6913
Eric Laurent2517af32020-11-25 15:31:27 +01006914bool AudioPolicyManager::isScoRequestedForComm() const {
6915 AudioDeviceTypeAddrVector devices;
6916 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6917 for (const auto &device : devices) {
6918 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6919 return true;
6920 }
6921 }
6922 return false;
6923}
6924
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006925bool AudioPolicyManager::isHearingAidUsedForComm() const {
6926 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6927 true /*fromCache*/);
6928 for (const auto &device : devices) {
6929 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6930 return true;
6931 }
6932 }
6933 return false;
6934}
6935
6936
Eric Laurente0720872014-03-11 09:30:41 -07006937void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006938{
François Gaffie53615e22015-03-19 09:24:12 +01006939 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006940 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006941 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006942 return;
6943 }
6944
Eric Laurent3a4311c2014-03-17 12:00:47 -07006945 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006946 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6947 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006948 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006949
6950 // if suspended, restore A2DP output if:
6951 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006952 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006953 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006954 //
Eric Laurentf732e072016-08-03 19:30:28 -07006955 // if not suspended, suspend A2DP output if:
6956 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006957 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006958 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006959 //
6960 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006961 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006962 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006963 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006964 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006965
6966 mpClientInterface->restoreOutput(a2dpOutput);
6967 mA2dpSuspended = false;
6968 }
6969 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006970 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006971 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006972 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006973 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006974
6975 mpClientInterface->suspendOutput(a2dpOutput);
6976 mA2dpSuspended = true;
6977 }
6978 }
6979}
6980
François Gaffie11d30102018-11-02 16:09:09 +01006981DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6982 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006983{
François Gaffie11d30102018-11-02 16:09:09 +01006984 DeviceVector devices;
6985
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006986 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006987 if (index >= 0) {
6988 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006989 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006990 ALOGV("%s device %s forced by patch %d", __func__,
6991 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6992 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006993 }
6994 }
6995
Dean Wheatley514b4312020-06-17 21:45:00 +10006996 // Do not retrieve engine device for outputs through MSD
6997 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6998 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6999 return outputDesc->devices();
7000 }
7001
Eric Laurent97ac8712018-07-27 18:59:02 -07007002 // Honor explicit routing requests only if no client using default routing is active on this
7003 // input: a specific app can not force routing for other apps by setting a preferred device.
7004 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007005 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007006 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007007 if (device != nullptr) {
7008 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007009 }
7010
François Gaffiea807ef92018-11-05 10:44:33 +01007011 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7012 // of setForceUse / Default Bus device here
7013 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7014 if (device != nullptr) {
7015 return DeviceVector(device);
7016 }
7017
François Gaffiec005e562018-11-06 15:04:49 +01007018 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7019 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7020 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307021 auto hasStreamActive = [&](auto stream) {
7022 return hasStream(streams, stream) && isStreamActive(stream, 0);
7023 };
Eric Laurent484e9272018-06-07 17:29:23 -07007024
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307025 auto doGetOutputDevicesForVoice = [&]() {
7026 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007027 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307028 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007029 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7030 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307031 };
7032
7033 // With low-latency playing on speaker, music on WFD, when the first low-latency
7034 // output is stopped, getNewOutputDevices checks for a product strategy
7035 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007036 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307037 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7038 // stream is associated to the output descriptor.
7039 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7040 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7041 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7042 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007043 // Retrieval of devices for voice DL is done on primary output profile, cannot
7044 // check the route (would force modifying configuration file for this profile)
7045 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7046 break;
7047 }
Eric Laurente552edb2014-03-10 17:42:56 -07007048 }
François Gaffiec005e562018-11-06 15:04:49 +01007049 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007050 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007051}
7052
François Gaffie11d30102018-11-02 16:09:09 +01007053sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7054 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007055{
François Gaffie11d30102018-11-02 16:09:09 +01007056 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007057
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007058 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007059 if (index >= 0) {
7060 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007061 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007062 ALOGV("getNewInputDevice() device %s forced by patch %d",
7063 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7064 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007065 }
7066 }
7067
Eric Laurent97ac8712018-07-27 18:59:02 -07007068 // Honor explicit routing requests only if no client using default routing is active on this
7069 // input: a specific app can not force routing for other apps by setting a preferred device.
7070 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007071 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7072 if (device != nullptr) {
7073 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007074 }
7075
Eric Laurentdc95a252018-04-12 12:46:56 -07007076 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007077 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007078 audio_attributes_t attributes;
7079 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007080 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007081 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7082 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007083 attributes = topClient->attributes();
7084 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007085 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007086 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007087 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7088 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007089 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007090 }
7091
Francois Gaffie716e1432019-01-14 16:58:59 +01007092 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7093 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007094 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007095 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007096 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007097 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007098
Eric Laurente552edb2014-03-10 17:42:56 -07007099 return device;
7100}
7101
Eric Laurent794fde22016-03-11 09:50:45 -08007102bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7103 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007104 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007105}
7106
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007107status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007108 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007109 if (devices == nullptr) {
7110 return BAD_VALUE;
7111 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007112
Andy Hung6d23c0f2022-02-16 09:37:15 -08007113 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007114 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7115 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007116 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007117 for (const auto& device : curDevices) {
7118 devices->push_back(device->getDeviceTypeAddr());
7119 }
7120 return NO_ERROR;
7121}
7122
Eric Laurente0720872014-03-11 09:30:41 -07007123void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007124 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007125 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007126 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007127 updateDevicesAndOutputs();
7128 break;
7129 default:
7130 break;
7131 }
7132}
7133
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007134uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007135
7136 // skip beacon mute management if a dedicated TTS output is available
7137 if (mTtsOutputAvailable) {
7138 return 0;
7139 }
7140
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007141 switch(event) {
7142 case STARTING_OUTPUT:
7143 mBeaconMuteRefCount++;
7144 break;
7145 case STOPPING_OUTPUT:
7146 if (mBeaconMuteRefCount > 0) {
7147 mBeaconMuteRefCount--;
7148 }
7149 break;
7150 case STARTING_BEACON:
7151 mBeaconPlayingRefCount++;
7152 break;
7153 case STOPPING_BEACON:
7154 if (mBeaconPlayingRefCount > 0) {
7155 mBeaconPlayingRefCount--;
7156 }
7157 break;
7158 }
7159
7160 if (mBeaconMuteRefCount > 0) {
7161 // any playback causes beacon to be muted
7162 return setBeaconMute(true);
7163 } else {
7164 // no other playback: unmute when beacon starts playing, mute when it stops
7165 return setBeaconMute(mBeaconPlayingRefCount == 0);
7166 }
7167}
7168
7169uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7170 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7171 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7172 // keep track of muted state to avoid repeating mute/unmute operations
7173 if (mBeaconMuted != mute) {
7174 // mute/unmute AUDIO_STREAM_TTS on all outputs
7175 ALOGV("\t muting %d", mute);
7176 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007177 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7178 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7179 ALOGV("\t no tts volume source available");
7180 return 0;
7181 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007182 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007183 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007184 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007185 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007186 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007187 maxLatency = latency;
7188 }
7189 }
7190 mBeaconMuted = mute;
7191 return maxLatency;
7192 }
7193 return 0;
7194}
7195
Eric Laurente0720872014-03-11 09:30:41 -07007196void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007197{
François Gaffiec005e562018-11-06 15:04:49 +01007198 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007199 mPreviousOutputs = mOutputs;
7200}
7201
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007202uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007203 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007204 uint32_t delayMs)
7205{
7206 // mute/unmute strategies using an incompatible device combination
7207 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7208 // if unmuting, unmute only after the specified delay
7209 if (outputDesc->isDuplicated()) {
7210 return 0;
7211 }
7212
7213 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007214 DeviceVector devices = outputDesc->devices();
7215 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007216
François Gaffiec005e562018-11-06 15:04:49 +01007217 auto productStrategies = mEngine->getOrderedProductStrategies();
7218 for (const auto &productStrategy : productStrategies) {
7219 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7220 DeviceVector curDevices =
7221 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7222 curDevices = curDevices.filter(outputDesc->supportedDevices());
7223 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007224 bool doMute = false;
7225
François Gaffiec005e562018-11-06 15:04:49 +01007226 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007227 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007228 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7229 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007230 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007231 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007232 }
Eric Laurent99401132014-05-07 19:48:15 -07007233 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007234 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007235 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007236 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007237 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007238 continue;
7239 }
François Gaffiec005e562018-11-06 15:04:49 +01007240 ALOGVV("%s() %s (curDevice %s)", __func__,
7241 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7242 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7243 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007244 if (mute) {
7245 // FIXME: should not need to double latency if volume could be applied
7246 // immediately by the audioflinger mixer. We must account for the delay
7247 // between now and the next time the audioflinger thread for this output
7248 // will process a buffer (which corresponds to one buffer size,
7249 // usually 1/2 or 1/4 of the latency).
7250 if (muteWaitMs < desc->latency() * 2) {
7251 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007252 }
7253 }
7254 }
7255 }
7256 }
7257 }
7258
Eric Laurent99401132014-05-07 19:48:15 -07007259 // temporary mute output if device selection changes to avoid volume bursts due to
7260 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007261 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007262 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007263
Eric Laurentdc462862016-07-19 12:29:53 -07007264 if (muteWaitMs < tempMuteWaitMs) {
7265 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007266 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007267
7268 // If recommended duration is defined, replace temporary mute duration to avoid
7269 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7270 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7271 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7272 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7273 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7274
François Gaffieaaac0fd2018-11-22 17:56:39 +01007275 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7276 // make sure that we do not start the temporary mute period too early in case of
7277 // delayed device change
7278 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7279 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007280 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007281 }
7282 }
7283
Eric Laurente552edb2014-03-10 17:42:56 -07007284 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7285 if (muteWaitMs > delayMs) {
7286 muteWaitMs -= delayMs;
7287 usleep(muteWaitMs * 1000);
7288 return muteWaitMs;
7289 }
7290 return 0;
7291}
7292
François Gaffie11d30102018-11-02 16:09:09 +01007293uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7294 const DeviceVector &devices,
7295 bool force,
7296 int delayMs,
7297 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02007298 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07007299{
jiabin3ff8d7d2022-12-13 06:27:44 +00007300 // TODO(b/262404095): Consider if the output need to be reopened.
François Gaffie11d30102018-11-02 16:09:09 +01007301 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007302 uint32_t muteWaitMs;
7303
7304 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01007305 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
7306 nullptr /* patchHandle */, requiresMuteCheck);
7307 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
7308 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07007309 return muteWaitMs;
7310 }
Eric Laurente552edb2014-03-10 17:42:56 -07007311
7312 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007313 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007314 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007315 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007316
François Gaffie11d30102018-11-02 16:09:09 +01007317 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7318
7319 if (!filteredDevices.isEmpty()) {
7320 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007321 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007322
7323 // if the outputs are not materially active, there is no need to mute.
7324 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007325 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007326 } else {
7327 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7328 muteWaitMs = 0;
7329 }
Eric Laurente552edb2014-03-10 17:42:56 -07007330
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007331 bool outputRouted = outputDesc->isRouted();
7332
Eric Laurent79ea9582020-06-11 18:49:24 -07007333 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7334 // output profile or if new device is not supported AND previous device(s) is(are) still
7335 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007336 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007337 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7338 // restore previous device after evaluating strategy mute state
7339 outputDesc->setDevices(prevDevices);
7340 return muteWaitMs;
7341 }
7342
Eric Laurente552edb2014-03-10 17:42:56 -07007343 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007344 // the requested device is AUDIO_DEVICE_NONE
7345 // OR the requested device is the same as current device
7346 // AND force is not specified
7347 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007348 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007349 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007350 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7351 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007352 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7353 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7354 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7355 }
Eric Laurente552edb2014-03-10 17:42:56 -07007356 return muteWaitMs;
7357 }
7358
François Gaffie11d30102018-11-02 16:09:09 +01007359 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007360
Eric Laurente552edb2014-03-10 17:42:56 -07007361 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007362 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007363 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007364 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007365 PatchBuilder patchBuilder;
7366 patchBuilder.addSource(outputDesc);
7367 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7368 for (const auto &filteredDevice : filteredDevices) {
7369 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007370 }
7371
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007372 // Add half reported latency to delayMs when muteWaitMs is null in order
7373 // to avoid disordered sequence of muting volume and changing devices.
7374 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7375 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007376 }
Eric Laurente552edb2014-03-10 17:42:56 -07007377
7378 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007379 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007380
7381 return muteWaitMs;
7382}
7383
Eric Laurentc75307b2015-03-17 15:29:32 -07007384status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007385 int delayMs,
7386 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007387{
Eric Laurent6a94d692014-05-20 11:18:06 -07007388 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007389 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7390 return INVALID_OPERATION;
7391 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007392 if (patchHandle) {
7393 index = mAudioPatches.indexOfKey(*patchHandle);
7394 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007395 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007396 }
7397 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007398 return INVALID_OPERATION;
7399 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007400 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007401 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007402 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007403 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007404 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007405 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007406 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007407 return status;
7408}
7409
7410status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007411 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007412 bool force,
7413 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007414{
7415 status_t status = NO_ERROR;
7416
Eric Laurent1f2f2232014-06-02 12:01:23 -07007417 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007418 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7419 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007420
François Gaffie11d30102018-11-02 16:09:09 +01007421 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007422 PatchBuilder patchBuilder;
7423 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007424 // AUDIO_SOURCE_HOTWORD is for internal use only:
7425 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007426 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7427 auto result = usecase;
7428 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7429 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7430 }
7431 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007432 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007433 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007434 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007435 }
7436 }
7437 return status;
7438}
7439
Eric Laurent6a94d692014-05-20 11:18:06 -07007440status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7441 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007442{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007443 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007444 ssize_t index;
7445 if (patchHandle) {
7446 index = mAudioPatches.indexOfKey(*patchHandle);
7447 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007448 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007449 }
7450 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007451 return INVALID_OPERATION;
7452 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007453 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007454 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007455 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007456 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007457 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007458 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007459 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007460 return status;
7461}
7462
François Gaffie11d30102018-11-02 16:09:09 +01007463sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007464 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007465 audio_format_t& format,
7466 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007467 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007468{
7469 // Choose an input profile based on the requested capture parameters: select the first available
7470 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007471 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007472 //
7473 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7474 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007475
Atneya Nair0f0a8032022-12-12 16:20:12 -08007476 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7477 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7478 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7479
7480 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007481
jiabin2fd710d2022-05-02 23:20:22 +00007482 for (;;) {
7483 sp<IOProfile> firstInexact = nullptr;
7484 uint32_t updatedSamplingRate = 0;
7485 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7486 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7487 for (const auto& hwModule : mHwModules) {
7488 for (const auto& profile : hwModule->getInputProfiles()) {
7489 // profile->log();
7490 //updatedFormat = format;
7491 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7492 &samplingRate /*updatedSamplingRate*/,
7493 format,
7494 &format, /*updatedFormat*/
7495 channelMask,
7496 &channelMask /*updatedChannelMask*/,
7497 // FIXME ugly cast
7498 (audio_output_flags_t) flags,
7499 true /*exactMatchRequiredForInputFlags*/)) {
7500 return profile;
7501 }
7502 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7503 samplingRate,
7504 &updatedSamplingRate,
7505 format,
7506 &updatedFormat,
7507 channelMask,
7508 &updatedChannelMask,
7509 // FIXME ugly cast
7510 (audio_output_flags_t) flags,
7511 false /*exactMatchRequiredForInputFlags*/)) {
7512 firstInexact = profile;
7513 }
7514 }
7515 }
7516
7517 if (firstInexact != nullptr) {
7518 samplingRate = updatedSamplingRate;
7519 format = updatedFormat;
7520 channelMask = updatedChannelMask;
7521 return firstInexact;
7522 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7523 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7524 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7525 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7526 flags = AUDIO_INPUT_FLAG_NONE;
7527 } else { // fail
7528 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7529 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7530 samplingRate, format, channelMask, oriFlags);
7531 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007532 }
7533 }
jiabin2fd710d2022-05-02 23:20:22 +00007534
7535 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007536}
7537
François Gaffieaaac0fd2018-11-22 17:56:39 +01007538float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7539 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007540 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007541 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007542{
jiabin9a3361e2019-10-01 09:38:30 -07007543 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007544
7545 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7546 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7547 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7548 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007549 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7550 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7551 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7552 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7553 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007554
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007555 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007556 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7557 mOutputs.isActive(ringVolumeSrc, 0)) {
7558 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007559 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007560 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007561 }
7562
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007563 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007564 if ((volumeSource != callVolumeSrc && (isInCall() ||
7565 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007566 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007567 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7568 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007569 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7570 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7571 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007572 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007573 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007574 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007575 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007576 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007577 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007578 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7579 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7580 // programmatically muted.
7581 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7582 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7583 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007584 bool exemptFromCapping =
7585 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7586 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007587 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7588 volumeSource, volumeDb);
7589 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007590 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7591 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7592 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007593 }
7594 }
Eric Laurente552edb2014-03-10 17:42:56 -07007595 // if a headset is connected, apply the following rules to ring tones and notifications
7596 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007597 // - always attenuate notifications volume by 6dB
7598 // - attenuate ring tones volume by 6dB unless music is not playing and
7599 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007600 // - if music is playing, always limit the volume to current music volume,
7601 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007602 if (!Intersection(deviceTypes,
7603 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7604 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007605 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7606 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007607 ((volumeSource == alarmVolumeSrc ||
7608 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007609 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7610 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7611 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007612 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7613 curves.canBeMuted()) {
7614
Eric Laurente552edb2014-03-10 17:42:56 -07007615 // when the phone is ringing we must consider that music could have been paused just before
7616 // by the music application and behave as if music was active if the last music track was
7617 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007618 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007619 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007620 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007621 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007622 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7623 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007624 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007625 float musicVolDb = computeVolume(musicCurves,
7626 musicVolumeSrc,
7627 musicCurves.getVolumeIndex(musicDevice),
7628 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007629 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7630 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7631 if (volumeDb > minVolDb) {
7632 volumeDb = minVolDb;
7633 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007634 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007635 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7636 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7637 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007638 // on A2DP, also ensure notification volume is not too low compared to media when
7639 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007640 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007641 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007642 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7643 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007644 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7645 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007646 }
7647 }
jiabin9a3361e2019-10-01 09:38:30 -07007648 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007649 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007650 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007651 }
7652 }
7653
François Gaffie43c73442018-11-08 08:21:55 +01007654 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007655}
7656
Eric Laurent3839bc02018-07-10 18:33:34 -07007657int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007658 VolumeSource fromVolumeSource,
7659 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007660{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007661 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007662 return srcIndex;
7663 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007664 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7665 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007666 float minSrc = (float)srcCurves.getVolumeIndexMin();
7667 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7668 float minDst = (float)dstCurves.getVolumeIndexMin();
7669 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007670
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007671 // preserve mute request or correct range
7672 if (srcIndex < minSrc) {
7673 if (srcIndex == 0) {
7674 return 0;
7675 }
7676 srcIndex = minSrc;
7677 } else if (srcIndex > maxSrc) {
7678 srcIndex = maxSrc;
7679 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007680 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7681}
7682
François Gaffieaaac0fd2018-11-22 17:56:39 +01007683status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7684 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007685 int index,
7686 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007687 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007688 int delayMs,
7689 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007690{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007691 // do not change actual attributes volume if the attributes is muted
7692 if (outputDesc->isMuted(volumeSource)) {
7693 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7694 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007695 return NO_ERROR;
7696 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007697 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7698 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7699 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7700 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007701
Eric Laurent2517af32020-11-25 15:31:27 +01007702 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007703 bool isHAUsed = isHearingAidUsedForComm();
7704
Eric Laurente552edb2014-03-10 17:42:56 -07007705 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007706 // if sco and call follow same curves, bypass forceUseForComm
7707 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007708 ((isVoiceVolSrc && isScoRequested) ||
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007709 (isBtScoVolSrc && !(isScoRequested || isHAUsed)))) {
Eric Laurent2517af32020-11-25 15:31:27 +01007710 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007711 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007712 // Do not return an error here as AudioService will always set both voice call
7713 // and bluetooth SCO volumes due to stream aliasing.
7714 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007715 }
jiabin9a3361e2019-10-01 09:38:30 -07007716 if (deviceTypes.empty()) {
7717 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007718 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007719
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007720 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7721 ALOGE("invalid volume index range");
7722 return BAD_VALUE;
7723 }
7724
jiabin9a3361e2019-10-01 09:38:30 -07007725 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7726 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007727 // Force VoIP volume to max for bluetooth SCO device except if muted
7728 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007729 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007730 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007731 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007732 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007733 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007734 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007735
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007736 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007737 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007738 // 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 +01007739 if (isVoiceVolSrc) {
7740 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007741 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007742 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007743 }
Eric Laurent18fba842016-03-31 14:41:26 -07007744 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007745 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7746 mLastVoiceVolume = voiceVolume;
7747 }
7748 }
Eric Laurente552edb2014-03-10 17:42:56 -07007749 return NO_ERROR;
7750}
7751
Eric Laurentc75307b2015-03-17 15:29:32 -07007752void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007753 const DeviceTypeSet& deviceTypes,
7754 int delayMs,
7755 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007756{
jiabincd510522020-01-22 09:40:55 -08007757 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007758 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7759 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7760 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007761 curves.getVolumeIndex(deviceTypes),
7762 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007763 }
7764}
7765
François Gaffiec005e562018-11-06 15:04:49 +01007766void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7767 bool on,
7768 const sp<AudioOutputDescriptor>& outputDesc,
7769 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007770 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007771{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007772 std::vector<VolumeSource> sourcesToMute;
7773 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7774 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7775 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007776 VolumeSource source = toVolumeSource(attributes, false);
7777 if ((source != VOLUME_SOURCE_NONE) &&
7778 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7779 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007780 sourcesToMute.push_back(source);
7781 }
Eric Laurente552edb2014-03-10 17:42:56 -07007782 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007783 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007784 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007785 }
7786
Eric Laurente552edb2014-03-10 17:42:56 -07007787}
7788
François Gaffieaaac0fd2018-11-22 17:56:39 +01007789void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7790 bool on,
7791 const sp<AudioOutputDescriptor>& outputDesc,
7792 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007793 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007794{
jiabin9a3361e2019-10-01 09:38:30 -07007795 if (deviceTypes.empty()) {
7796 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007797 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007798 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007799 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007800 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007801 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007802 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007803 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7804 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007805 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007806 }
7807 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007808 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7809 // ignored
7810 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007811 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007812 if (!outputDesc->isMuted(volumeSource)) {
7813 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007814 return;
7815 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007816 if (outputDesc->decMuteCount(volumeSource) == 0) {
7817 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007818 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007819 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007820 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007821 delayMs);
7822 }
7823 }
7824}
7825
François Gaffie53615e22015-03-19 09:24:12 +01007826bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7827{
François Gaffiec005e562018-11-06 15:04:49 +01007828 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007829 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7830 return true;
7831 }
7832
7833 // has known usage?
7834 switch (paa->usage) {
7835 case AUDIO_USAGE_UNKNOWN:
7836 case AUDIO_USAGE_MEDIA:
7837 case AUDIO_USAGE_VOICE_COMMUNICATION:
7838 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7839 case AUDIO_USAGE_ALARM:
7840 case AUDIO_USAGE_NOTIFICATION:
7841 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7842 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7843 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7844 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7845 case AUDIO_USAGE_NOTIFICATION_EVENT:
7846 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7847 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7848 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7849 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007850 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007851 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007852 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007853 case AUDIO_USAGE_EMERGENCY:
7854 case AUDIO_USAGE_SAFETY:
7855 case AUDIO_USAGE_VEHICLE_STATUS:
7856 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007857 break;
7858 default:
7859 return false;
7860 }
7861 return true;
7862}
7863
François Gaffie2110e042015-03-24 08:41:51 +01007864audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7865{
7866 return mEngine->getForceUse(usage);
7867}
7868
Eric Laurent96d1dda2022-03-14 17:14:19 +01007869bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007870 return isStateInCall(mEngine->getPhoneState());
7871}
7872
Eric Laurent96d1dda2022-03-14 17:14:19 +01007873bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007874 return is_state_in_call(state);
7875}
7876
Eric Laurentf9cccec2022-11-16 19:12:00 +01007877bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007878 audio_mode_t mode = mEngine->getPhoneState();
7879 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007880 || (mode == AUDIO_MODE_CALL_SCREEN)
7881 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007882}
7883
Eric Laurentf9cccec2022-11-16 19:12:00 +01007884bool AudioPolicyManager::isInCallOrScreening() const {
7885 audio_mode_t mode = mEngine->getPhoneState();
7886 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7887}
7888
Eric Laurentd60560a2015-04-10 11:31:20 -07007889void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7890{
7891 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007892 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007893 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007894 sourceDesc->sinkDevice()->equals(deviceDesc))
7895 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007896 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007897 }
7898 }
7899
7900 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7901 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7902 bool release = false;
7903 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7904 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7905 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7906 source->ext.device.type == deviceDesc->type()) {
7907 release = true;
7908 }
7909 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007910 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007911 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7912 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7913 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007914 sink->ext.device.type == deviceDesc->type() &&
7915 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7916 || strncmp(sink->ext.device.address, address,
7917 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007918 release = true;
7919 }
7920 }
7921 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007922 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7923 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007924 }
7925 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007926
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007927 mInputs.clearSessionRoutesForDevice(deviceDesc);
7928
Francois Gaffie716e1432019-01-14 16:58:59 +01007929 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007930}
7931
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007932void AudioPolicyManager::modifySurroundFormats(
7933 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007934 std::unordered_set<audio_format_t> enforcedSurround(
7935 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007936 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7937 for (const auto& pair : mConfig.getSurroundFormats()) {
7938 allSurround.insert(pair.first);
7939 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7940 }
Phil Burk09bc4612016-02-24 15:58:15 -08007941
7942 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7943 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007944 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007945 // This is the resulting set of formats depending on the surround mode:
7946 // 'all surround' = allSurround
7947 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7948 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7949 // 'manual surround' = mManualSurroundFormats
7950 // AUTO: formats v 'enforced surround'
7951 // ALWAYS: formats v 'all surround' v 'enforced surround'
7952 // NEVER: formats ^ 'non-surround'
7953 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007954
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007955 std::unordered_set<audio_format_t> formatSet;
7956 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7957 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007958 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007959 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007960 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007961 formatSet.insert(*formatIter);
7962 }
7963 }
7964 } else {
7965 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7966 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007967 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007968
jiabin81772902018-04-02 17:52:27 -07007969 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007970 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007971 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7972 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7973 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007974 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007975 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7976 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7977 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007978 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007979 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007980 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007981 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007982 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007983 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007984}
7985
jiabin06e4bab2019-07-29 10:13:34 -07007986void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7987 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007988 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7989 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7990
7991 // If NEVER, then remove support for channelMasks > stereo.
7992 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007993 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7994 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007995 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007996 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007997 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007998 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007999 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008000 }
8001 }
jiabin81772902018-04-02 17:52:27 -07008002 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8003 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8004 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008005 bool supports5dot1 = false;
8006 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008007 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008008 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8009 supports5dot1 = true;
8010 break;
8011 }
8012 }
8013 // If not then add 5.1 support.
8014 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008015 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008016 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008017 }
Phil Burk09bc4612016-02-24 15:58:15 -08008018 }
8019}
8020
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008021void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008022 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01008023 AudioProfileVector &profiles)
8024{
8025 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008026 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07008027
François Gaffie112b0af2015-11-19 16:13:25 +01008028 // Format MUST be checked first to update the list of AudioProfile
8029 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008030 reply = mpClientInterface->getParameters(
8031 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07008032 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008033 AudioParameter repliedParameters(reply);
8034 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008035 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01008036 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
8037 return;
8038 }
Phil Burk09bc4612016-02-24 15:58:15 -08008039 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01008040 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08008041 if (device == AUDIO_DEVICE_OUT_HDMI
8042 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008043 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07008044 }
jiabin3e277cc2019-09-10 14:27:34 -07008045 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01008046 }
François Gaffie112b0af2015-11-19 16:13:25 +01008047
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008048 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07008049 ChannelMaskSet channelMasks;
8050 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01008051 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07008052 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01008053
8054 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008055 reply = mpClientInterface->getParameters(
8056 ioHandle,
8057 requestedParameters.toString() + ";" +
8058 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01008059 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008060 AudioParameter repliedParameters(reply);
8061 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008062 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008063 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01008064 }
8065 }
8066 if (profiles.hasDynamicChannelsFor(format)) {
8067 reply = mpClientInterface->getParameters(ioHandle,
8068 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07008069 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01008070 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008071 AudioParameter repliedParameters(reply);
8072 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008073 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008074 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008075 if (device == AUDIO_DEVICE_OUT_HDMI
8076 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008077 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07008078 }
François Gaffie112b0af2015-11-19 16:13:25 +01008079 }
8080 }
jiabin3e277cc2019-09-10 14:27:34 -07008081 addDynamicAudioProfileAndSort(
8082 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01008083 }
8084}
Eric Laurentd60560a2015-04-10 11:31:20 -07008085
Mikhail Naganovdc769682018-05-04 15:34:08 -07008086status_t AudioPolicyManager::installPatch(const char *caller,
8087 audio_patch_handle_t *patchHandle,
8088 AudioIODescriptorInterface *ioDescriptor,
8089 const struct audio_patch *patch,
8090 int delayMs)
8091{
8092 ssize_t index = mAudioPatches.indexOfKey(
8093 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8094 *patchHandle : ioDescriptor->getPatchHandle());
8095 sp<AudioPatch> patchDesc;
8096 status_t status = installPatch(
8097 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8098 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008099 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008100 }
8101 return status;
8102}
8103
8104status_t AudioPolicyManager::installPatch(const char *caller,
8105 ssize_t index,
8106 audio_patch_handle_t *patchHandle,
8107 const struct audio_patch *patch,
8108 int delayMs,
8109 uid_t uid,
8110 sp<AudioPatch> *patchDescPtr)
8111{
8112 sp<AudioPatch> patchDesc;
8113 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8114 if (index >= 0) {
8115 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008116 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008117 }
8118
8119 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8120 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8121 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8122 if (status == NO_ERROR) {
8123 if (index < 0) {
8124 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008125 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008126 } else {
8127 patchDesc->mPatch = *patch;
8128 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008129 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008130 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008131 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008132 }
8133 nextAudioPortGeneration();
8134 mpClientInterface->onAudioPatchListUpdate();
8135 }
8136 if (patchDescPtr) *patchDescPtr = patchDesc;
8137 return status;
8138}
8139
jiabinbce0c1d2020-10-05 11:20:18 -07008140bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8141{
8142 const TrackClientVector activeClients = output->getActiveClients();
8143 if (activeClients.empty()) {
8144 return true;
8145 }
8146 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8147 if (index < 0) {
8148 ALOGE("%s, no audio patch found while there are active clients on output %d",
8149 __func__, output->getId());
8150 return false;
8151 }
8152 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8153 DeviceVector routedDevices;
8154 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8155 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8156 patchDesc->mPatch.sinks[i].id);
8157 if (device == nullptr) {
8158 ALOGE("%s, no audio device found with id(%d)",
8159 __func__, patchDesc->mPatch.sinks[i].id);
8160 return false;
8161 }
8162 routedDevices.add(device);
8163 }
8164 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008165 if (client->isInvalid()) {
8166 // No need to take care about invalidated clients.
8167 continue;
8168 }
jiabinbce0c1d2020-10-05 11:20:18 -07008169 sp<DeviceDescriptor> preferredDevice =
8170 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8171 if (mEngine->getOutputDevicesForAttributes(
8172 client->attributes(), preferredDevice, false) == routedDevices) {
8173 return false;
8174 }
8175 }
8176 return true;
8177}
8178
8179sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008180 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008181 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8182 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008183{
8184 for (const auto& device : devices) {
8185 // TODO: This should be checking if the profile supports the device combo.
8186 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008187 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8188 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008189 return nullptr;
8190 }
8191 }
8192 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8193 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008194 status_t status = desc->open(halConfig, mixerConfig, devices,
8195 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008196 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008197 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008198 return nullptr;
8199 }
8200
8201 // Here is where the out_set_parameters() for card & device gets called
8202 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8203 const audio_devices_t deviceType = device->type();
8204 const String8 &address = String8(device->address().c_str());
8205 if (!address.isEmpty()) {
8206 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8207 mpClientInterface->setParameters(output, String8(param));
8208 free(param);
8209 }
8210 updateAudioProfiles(device, output, profile->getAudioProfiles());
8211 if (!profile->hasValidAudioProfile()) {
8212 ALOGW("%s() missing param", __func__);
8213 desc->close();
8214 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008215 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8216 // Reopen the output with the best audio profile picked by APM when the profile supports
8217 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008218 desc->close();
8219 output = AUDIO_IO_HANDLE_NONE;
8220 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8221 profile->pickAudioProfile(
8222 config.sample_rate, config.channel_mask, config.format);
8223 config.offload_info.sample_rate = config.sample_rate;
8224 config.offload_info.channel_mask = config.channel_mask;
8225 config.offload_info.format = config.format;
8226
jiabina84c3d32022-12-02 18:59:55 +00008227 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008228 if (status != NO_ERROR) {
8229 return nullptr;
8230 }
8231 }
8232
8233 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008234
baek.kim -61c20122022-07-27 10:05:32 +00008235 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8236 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8237
jiabinbce0c1d2020-10-05 11:20:18 -07008238 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8239 sp<AudioPolicyMix> policyMix;
8240 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8241 policyMix->setOutput(desc);
8242 desc->mPolicyMix = policyMix;
8243 } else {
8244 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
8245 address.string());
8246 }
8247
baek.kim -61c20122022-07-27 10:05:32 +00008248 } else if (hasPrimaryOutput() && speaker != nullptr
8249 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008250 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8251 // no duplicated output for:
8252 // - direct outputs
8253 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008254 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008255 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8256
8257 //TODO: configure audio effect output stage here
8258
8259 // open a duplicating output thread for the new output and the primary output
8260 sp<SwAudioOutputDescriptor> dupOutputDesc =
8261 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8262 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8263 if (status == NO_ERROR) {
8264 // add duplicated output descriptor
8265 addOutput(duplicatedOutput, dupOutputDesc);
8266 } else {
8267 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8268 mPrimaryOutput->mIoHandle, output);
8269 desc->close();
8270 removeOutput(output);
8271 nextAudioPortGeneration();
8272 return nullptr;
8273 }
8274 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008275 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8276 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8277 mPrimaryOutput = desc;
8278 }
jiabinbce0c1d2020-10-05 11:20:18 -07008279 return desc;
8280}
8281
jiabinf1c73972022-04-14 16:28:52 -07008282status_t AudioPolicyManager::getDevicesForAttributes(
8283 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8284 // Devices are determined in the following precedence:
8285 //
8286 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8287 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8288 //
8289 // If no such dynamic policy then
8290 // 2) Devices containing an active client using setPreferredDevice
8291 // with same strategy as the attributes.
8292 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8293 //
8294 // If no corresponding active client with setPreferredDevice then
8295 // 3) Devices associated with the strategy determined by the attributes
8296 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8297 //
8298 // See related getOutputForAttrInt().
8299
8300 // check dynamic policies but only for primary descriptors (secondary not used for audible
8301 // audio routing, only used for duplication for playback capture)
8302 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008303 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008304 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008305 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8306 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8307 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008308 if (status != OK) {
8309 return status;
8310 }
8311
8312 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8313 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8314 // as they are unaffected by device/stream volume
8315 // (per SwAudioOutputDescriptor::isFixedVolume()).
8316 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8317 ) {
8318 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8319 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8320 devices.add(deviceDesc);
8321 } else {
8322 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8323 // which selects setPreferredDevice if active. This means forVolume call
8324 // will take an active setPreferredDevice, if such exists.
8325
8326 devices = mEngine->getOutputDevicesForAttributes(
8327 attr, nullptr /* preferredDevice */, false /* fromCache */);
8328 }
8329
8330 if (forVolume) {
8331 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8332 // for single volume control in AudioService (such relationship should exist if
8333 // SPEAKER_SAFE is present).
8334 //
8335 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8336 DeviceVector speakerSafeDevices =
8337 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8338 if (!speakerSafeDevices.isEmpty()) {
8339 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8340 devices.remove(speakerSafeDevices);
8341 }
8342 }
8343
8344 return NO_ERROR;
8345}
8346
8347status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8348 AudioProfileVector& audioProfiles,
8349 uint32_t flags,
8350 bool isInput) {
8351 for (const auto& hwModule : mHwModules) {
8352 // the MSD module checks for different conditions
8353 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8354 continue;
8355 }
8356 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8357 : hwModule->getOutputProfiles();
8358 for (const auto& profile : ioProfiles) {
8359 if (!profile->areAllDevicesSupported(devices) ||
8360 !profile->isCompatibleProfileForFlags(
8361 flags, false /*exactMatchRequiredForInputFlags*/)) {
8362 continue;
8363 }
8364 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8365 }
8366 }
8367
8368 if (!isInput) {
8369 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8370 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8371 if (msdModule != nullptr) {
8372 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8373 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8374 for (const auto &profile: msdModule->getOutputProfiles()) {
8375 if (!profile->asAudioPort()->isDirectOutput()) {
8376 continue;
8377 }
8378 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8379 }
8380 } else {
8381 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8382 }
8383 }
8384 }
8385
8386 return NO_ERROR;
8387}
8388
jiabin3ff8d7d2022-12-13 06:27:44 +00008389sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8390 const audio_config_t *config,
8391 audio_output_flags_t flags,
8392 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008393 closeOutput(outputDesc->mIoHandle);
8394 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8395 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8396 if (preferredOutput == nullptr) {
8397 ALOGE("%s failed to reopen output device=%d, caller=%s",
8398 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008399 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008400 return preferredOutput;
8401}
8402
8403void AudioPolicyManager::reopenOutputsWithDevices(
8404 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8405 for (const auto& [output, devices] : outputsToReopen) {
8406 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8407 closeOutput(output);
8408 openOutputWithProfileAndDevice(desc->mProfile, devices);
8409 }
jiabina84c3d32022-12-02 18:59:55 +00008410}
8411
jiabinc44b3462022-12-08 12:52:31 -08008412PortHandleVector AudioPolicyManager::getClientsForStream(
8413 audio_stream_type_t streamType) const {
8414 PortHandleVector clients;
8415 for (size_t i = 0; i < mOutputs.size(); ++i) {
8416 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8417 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8418 }
8419 return clients;
8420}
8421
8422void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8423 PortHandleVector clients;
8424 for (auto stream : streams) {
8425 PortHandleVector clientsForStream = getClientsForStream(stream);
8426 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8427 }
8428 mpClientInterface->invalidateTracks(clients);
8429}
8430
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008431} // namespace android