blob: dd27ca48f33564b9a6053b07de69f6f4c1b8dd6d [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Eric Laurent16c66dd2019-05-01 17:54:10 -070032#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070033#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000034#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080036#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080037#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080038#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110039#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070040
41#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010042#include <android/media/audio/common/AudioPort.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070043#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070044#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070046#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070047#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070048#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070049#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070050#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070051#include <utils/Log.h>
52
Eric Laurentd4692962014-05-05 18:13:44 -070053#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010054#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070055
Eric Laurent3b73df72014-03-11 09:06:29 -070056namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070057
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010058using android::media::audio::common::AudioDevice;
59using android::media::audio::common::AudioDeviceAddress;
60using android::media::audio::common::AudioPortDeviceExt;
61using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000062using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070063
Eric Laurentdc462862016-07-19 12:29:53 -070064//FIXME: workaround for truncated touch sounds
65// to be removed when the problem is handled by system UI
66#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070067
68// Largest difference in dB on earpiece in call between the voice volume and another
69// media / notification / system volume.
70constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
71
jiabin06e4bab2019-07-29 10:13:34 -070072template <typename T>
73bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
74{
75 if (left.size() != right.size()) {
76 return false;
77 }
78 for (size_t index = 0; index < right.size(); index++) {
79 if (left[index] != right[index]) {
80 return false;
81 }
82 }
83 return true;
84}
85
86template <typename T>
87bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
88{
89 return !(left == right);
90}
91
Eric Laurente552edb2014-03-10 17:42:56 -070092// ----------------------------------------------------------------------------
93// AudioPolicyInterface implementation
94// ----------------------------------------------------------------------------
95
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010096status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
97 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
98 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -080099 nextAudioPortGeneration();
100 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800101}
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
104 audio_policy_dev_state_t state,
105 const char* device_address,
106 const char* device_name,
107 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800108 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100109 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
110 status == OK) {
111 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
112 } else {
113 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
114 return status;
115 }
116}
117
François Gaffie11d30102018-11-02 16:09:09 +0100118void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
119 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200120{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000121 audio_port_v7 devicePort;
122 device->toAudioPort(&devicePort);
123 if (status_t status = mpClientInterface->setDeviceConnectedState(
124 &devicePort, state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
125 status != OK) {
126 ALOGE("Error %d while setting connected state for device %s", status,
127 device->getDeviceTypeAddr().toString(false).c_str());
128 }
François Gaffie44481e72016-04-20 07:49:57 +0200129}
130
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100131status_t AudioPolicyManager::setDeviceConnectionStateInt(
132 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
133 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100134 if (port.ext.getTag() != AudioPortExt::device) {
135 return BAD_VALUE;
136 }
137 audio_devices_t device_type;
138 std::string device_address;
139 if (status_t status = aidl2legacy_AudioDevice_audio_device(
140 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
141 status != OK) {
142 return status;
143 };
144 const char* device_name = port.name.c_str();
145 // connect/disconnect only 1 device at a time
146 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
147 return BAD_VALUE;
148
149 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
150 device_type, device_address.c_str(), device_name, encodedFormat,
151 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000152 if (device == nullptr) {
153 return INVALID_OPERATION;
154 }
155 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
156 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
157 }
158 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100159}
160
François Gaffie11d30102018-11-02 16:09:09 +0100161status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800162 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100163 const char* device_address,
164 const char* device_name,
165 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800166 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100167 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
168 status == OK) {
169 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
170 } else {
171 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
172 return status;
173 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700174}
Paul McLeane743a472015-01-28 11:07:31 -0800175
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700176status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
177 audio_policy_dev_state_t state)
178{
Eric Laurente552edb2014-03-10 17:42:56 -0700179 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700180 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700181 SortedVector <audio_io_handle_t> outputs;
182
François Gaffie11d30102018-11-02 16:09:09 +0100183 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700184
Eric Laurente552edb2014-03-10 17:42:56 -0700185 // save a copy of the opened output descriptors before any output is opened or closed
186 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
187 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100188
189 bool wasLeUnicastActive = isLeUnicastActive();
190
Eric Laurente552edb2014-03-10 17:42:56 -0700191 switch (state)
192 {
193 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800194 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700195 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100196 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700197 return INVALID_OPERATION;
198 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800199 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700200 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700201
Eric Laurente552edb2014-03-10 17:42:56 -0700202 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200203 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700204 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700205 }
206
François Gaffie44481e72016-04-20 07:49:57 +0200207 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
208 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100209 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200210
François Gaffie11d30102018-11-02 16:09:09 +0100211 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
212 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200213
Francois Gaffie716e1432019-01-14 16:58:59 +0100214 mHwModules.cleanUpForDevice(device);
215
François Gaffie11d30102018-11-02 16:09:09 +0100216 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700217 return INVALID_OPERATION;
218 }
François Gaffie2110e042015-03-24 08:41:51 +0100219
jiabin1c4794b2020-05-05 10:08:05 -0700220 // Populate encapsulation information when a output device is connected.
221 device->setEncapsulationInfoFromHal(mpClientInterface);
222
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700223 // outputs should never be empty here
224 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
225 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100226 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800227
Eric Laurent3ae5f312015-02-03 17:12:08 -0800228 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700229 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700230 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700231 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100232 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700233 return INVALID_OPERATION;
234 }
235
François Gaffie11d30102018-11-02 16:09:09 +0100236 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700237
Paul McLeane743a472015-01-28 11:07:31 -0800238 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100239 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700240
Eric Laurente552edb2014-03-10 17:42:56 -0700241 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100242 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700243
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100244 mOutputs.clearSessionRoutesForDevice(device);
245
François Gaffie11d30102018-11-02 16:09:09 +0100246 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100247
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800248 // Reset active device codec
249 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
250
Kriti Dangef6be8f2020-11-05 11:58:19 +0100251 // remove device from mReportedFormatsMap cache
252 mReportedFormatsMap.erase(device);
253
jiabina84c3d32022-12-02 18:59:55 +0000254 // remove preferred mixer configurations
255 mPreferredMixerAttrInfos.erase(device->getId());
256
Eric Laurente552edb2014-03-10 17:42:56 -0700257 } break;
258
259 default:
François Gaffie11d30102018-11-02 16:09:09 +0100260 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700261 return BAD_VALUE;
262 }
263
Eric Laurent736a1022019-03-27 18:28:46 -0700264 // Propagate device availability to Engine
265 setEngineDeviceConnectionState(device, state);
266
Eric Laurentae970022019-01-29 14:25:04 -0800267 // No need to evaluate playback routing when connecting a remote submix
268 // output device used by a dynamic policy of type recorder as no
269 // playback use case is affected.
270 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700271 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800272 for (audio_io_handle_t output : outputs) {
273 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800274 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
275 if (policyMix != nullptr
276 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700277 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800278 doCheckForDeviceAndOutputChanges = false;
279 break;
280 }
281 }
282 }
283
284 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700285 // outputs must be closed after checkOutputForAllStrategies() is executed
286 if (!outputs.isEmpty()) {
287 for (audio_io_handle_t output : outputs) {
288 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100289 // close unused outputs after device disconnection or direct outputs that have
290 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200291 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200292 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
293 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200294 (desc->mDirectOpenCount == 0))
295 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
296 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200297 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700298 closeOutput(output);
299 }
Eric Laurente552edb2014-03-10 17:42:56 -0700300 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700301 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
302 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700303 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700304 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800305 };
306
307 if (doCheckForDeviceAndOutputChanges) {
308 checkForDeviceAndOutputChanges(checkCloseOutputs);
309 } else {
310 checkCloseOutputs();
311 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100312 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100313 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700314 const DeviceVector activeMediaDevices =
315 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000316 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700317 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700318 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530319 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
320 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100321 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700322 // do not force device change on duplicated output because if device is 0, it will
323 // also force a device 0 for the two outputs it is duplicated to which may override
324 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100325 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100326 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700327 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700328 // always force when disconnecting (a non-duplicated device)
329 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin3ff8d7d2022-12-13 06:27:44 +0000330 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
331 // If the device is using preferred mixer attributes, the output need to reopen
332 // with default configuration when the new selected devices are different from
333 // current routing devices
334 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
335 continue;
336 }
François Gaffie11d30102018-11-02 16:09:09 +0100337 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700338 }
jiabinbce0c1d2020-10-05 11:20:18 -0700339 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000340 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700341 desc->supportsDevicesForPlayback(activeMediaDevices)) {
342 // Reopen the output to query the dynamic profiles when there is not active
343 // clients or all active clients will be rerouted. Otherwise, set the flag
344 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
345 // can be reopened to query dynamic profiles when all clients are inactive.
346 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000347 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700348 } else {
349 desc->mPendingReopenToQueryProfiles = true;
350 }
351 }
352 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
353 // Clear the flag that previously set for re-querying profiles.
354 desc->mPendingReopenToQueryProfiles = false;
355 }
356 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000357 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700358
Eric Laurentd60560a2015-04-10 11:31:20 -0700359 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100360 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700361 }
362
Eric Laurent96d1dda2022-03-14 17:14:19 +0100363 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
364
Eric Laurent72aa32f2014-05-30 18:51:48 -0700365 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700366 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700367 } // end if is output device
368
Eric Laurente552edb2014-03-10 17:42:56 -0700369 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700370 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100371 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700372 switch (state)
373 {
374 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700375 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700376 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100377 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700378 return INVALID_OPERATION;
379 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700380
381 if (mAvailableInputDevices.add(device) < 0) {
382 return NO_MEMORY;
383 }
384
François Gaffie44481e72016-04-20 07:49:57 +0200385 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
386 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100387 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200388
Eric Laurent0dd51852019-04-19 18:18:58 -0700389 if (checkInputsForDevice(device, state) != NO_ERROR) {
390 mAvailableInputDevices.remove(device);
391
François Gaffie11d30102018-11-02 16:09:09 +0100392 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100393
394 mHwModules.cleanUpForDevice(device);
395
Eric Laurentd4692962014-05-05 18:13:44 -0700396 return INVALID_OPERATION;
397 }
398
Eric Laurentd4692962014-05-05 18:13:44 -0700399 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700400
401 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700402 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700403 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100404 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700405 return INVALID_OPERATION;
406 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700407
François Gaffie11d30102018-11-02 16:09:09 +0100408 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700409
410 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100411 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700412
François Gaffie11d30102018-11-02 16:09:09 +0100413 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700414
415 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100416
417 // remove device from mReportedFormatsMap cache
418 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700419 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700420
421 default:
François Gaffie11d30102018-11-02 16:09:09 +0100422 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700423 return BAD_VALUE;
424 }
425
Eric Laurent736a1022019-03-27 18:28:46 -0700426 // Propagate device availability to Engine
427 setEngineDeviceConnectionState(device, state);
428
Eric Laurent0dd51852019-04-19 18:18:58 -0700429 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700430 // As the input device list can impact the output device selection, update
431 // getDeviceForStrategy() cache
432 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700433
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100434 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200435 // Reconnect Audio Source
436 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
437 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
438 checkAudioSourceForAttributes(attributes);
439 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700440 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100441 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700442 }
443
Eric Laurentb52c1522014-05-20 11:27:36 -0700444 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700445 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700446 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700447
François Gaffie11d30102018-11-02 16:09:09 +0100448 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700449 return BAD_VALUE;
450}
451
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100452status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
453 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800454 media::AudioPortFw* aidlPort) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100455 DeviceDescriptorBase devDescr(device, device_address);
456 devDescr.setName(device_name);
457 return devDescr.writeToParcelable(aidlPort);
458}
459
Eric Laurent736a1022019-03-27 18:28:46 -0700460void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
461 audio_policy_dev_state_t state) {
462
463 // the Engine does not have to know about remote submix devices used by dynamic audio policies
464 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
465 return;
466 }
467 mEngine->setDeviceConnectionState(device, state);
468}
469
470
Eric Laurente0720872014-03-11 09:30:41 -0700471audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100472 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700473{
Eric Laurent634b7142016-04-20 13:48:02 -0700474 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800475 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
476 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700477 (strlen(device_address) != 0)/*matchAddress*/);
478
479 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100480 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700481 device, device_address);
482 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
483 }
François Gaffie53615e22015-03-19 09:24:12 +0100484
Eric Laurent3a4311c2014-03-17 12:00:47 -0700485 DeviceVector *deviceVector;
486
Eric Laurente552edb2014-03-10 17:42:56 -0700487 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700488 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700489 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700490 deviceVector = &mAvailableInputDevices;
491 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100492 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700493 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700494 }
Eric Laurent634b7142016-04-20 13:48:02 -0700495
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800496 return (deviceVector->getDevice(
497 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700498 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800499}
500
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800501status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
502 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800503 const char *device_name,
504 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800505{
506 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700507 String8 reply;
508 AudioParameter param;
509 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800510
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800511 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
512 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800513
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800514 // connect/disconnect only 1 device at a time
515 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
516
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800517 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700518 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800519 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520 // Nothing to do: device is not connected
521 return NO_ERROR;
522 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800523 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800524
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700525 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800526 // configure codecs.
527 // Handle two specific cases by sending a set parameter to
528 // configure A2DP codecs. No need to toggle device state.
529 // Case 1: A2DP active device switches from primary to primary
530 // module
531 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200532 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700533 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800534 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
535 if (availablePrimaryOutputDevices().contains(devDesc) &&
536 (module != 0 && module->getHandle() == primaryHandle)) {
537 reply = mpClientInterface->getParameters(
538 AUDIO_IO_HANDLE_NONE,
539 String8(AudioParameter::keyReconfigA2dpSupported));
540 AudioParameter repliedParameters(reply);
541 repliedParameters.getInt(
542 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
543 if (isReconfigA2dpSupported) {
544 const String8 key(AudioParameter::keyReconfigA2dp);
545 param.add(key, String8("true"));
546 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
547 devDesc->setEncodedFormat(encodedFormat);
548 return NO_ERROR;
549 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700550 }
551 }
cnx421bd2dcc42020-07-11 14:58:44 +0800552 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
553 for (size_t i = 0; i < mOutputs.size(); i++) {
554 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
555 // mute media strategies and delay device switch by the largest
556 // This avoid sending the music tail into the earpiece or headset.
557 setStrategyMute(musicStrategy, true, desc);
558 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
559 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
560 nullptr, true /*fromCache*/).types());
561 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800562 // Toggle the device state: UNAVAILABLE -> AVAILABLE
563 // This will force reading again the device configuration
564 status = setDeviceConnectionState(device,
565 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800566 device_address, device_name,
567 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800568 if (status != NO_ERROR) {
569 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
570 status);
571 return status;
572 }
573
574 status = setDeviceConnectionState(device,
575 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800576 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800577 if (status != NO_ERROR) {
578 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
579 status);
580 return status;
581 }
582
583 return NO_ERROR;
584}
585
Pattydd807582021-11-04 21:01:03 +0800586status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
587 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800588{
Pattydd807582021-11-04 21:01:03 +0800589 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800590 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800591 std::unordered_set<audio_format_t> formatSet;
592 sp<HwModule> primaryModule =
593 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700594 if (primaryModule == nullptr) {
595 ALOGE("%s() unable to get primary module", __func__);
596 return NO_INIT;
597 }
Pattydd807582021-11-04 21:01:03 +0800598
599 DeviceTypeSet audioDeviceSet;
600
601 switch(device) {
602 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
603 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
604 break;
605 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800606 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
607 break;
608 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
609 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800610 break;
611 default:
612 ALOGE("%s() device type 0x%08x not supported", __func__, device);
613 return BAD_VALUE;
614 }
615
jiabin9a3361e2019-10-01 09:38:30 -0700616 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800617 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800618 for (const auto& device : declaredDevices) {
619 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800620 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800621 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800622 return status;
623}
624
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100625DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
626{
627 DeviceVector rxSinkdevices{};
628 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
629 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
630 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
631 auto rxSinkDevice = rxSinkdevices.itemAt(0);
632 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
633 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
634 // retrieve Rx Source device descriptor
635 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
636 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
637
638 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
639 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
640 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
641 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
642 return DeviceVector(rxSinkDevice);
643 }
644 }
645 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
646 // the device returned is not necessarily reachable via this output
647 // (filter later by setOutputDevices())
648 return getNewOutputDevices(mPrimaryOutput, fromCache);
649}
650
651status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
652{
653 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
654 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
655 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
656 }
657 return INVALID_OPERATION;
658}
659
660status_t AudioPolicyManager::updateCallRoutingInternal(
661 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700662{
663 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100664 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700665 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700666 if(!hasPrimaryOutput() ||
667 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100668 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700669 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100670 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100671
Francois Gaffie716e1432019-01-14 16:58:59 +0100672 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100673 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Eric Laurentcedd5b52023-03-22 00:03:31 +0000674 if (txSourceDevice == nullptr) {
675 ALOGE("%s() selected input device not available", __func__);
676 return INVALID_OPERATION;
677 }
François Gaffiec005e562018-11-06 15:04:49 +0100678
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100679 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100680 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700681
Francois Gaffie601801d2021-06-22 13:27:39 +0200682 disconnectTelephonyAudioSource(mCallRxSourceClient);
683 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700684
François Gaffie9eb18552018-11-05 10:33:26 +0100685 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700686 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100687 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700688 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100689 // retrieve Rx Source and Tx Sink device descriptors
690 sp<DeviceDescriptor> rxSourceDevice =
691 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
692 String8(),
693 AUDIO_FORMAT_DEFAULT);
694 sp<DeviceDescriptor> txSinkDevice =
695 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
696 String8(),
697 AUDIO_FORMAT_DEFAULT);
698
699 // RX and TX Telephony device are declared by Primary Audio HAL
700 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
701 (telephonyRxModule->getHalVersionMajor() >= 3)) {
702 if (rxSourceDevice == 0 || txSinkDevice == 0) {
703 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100704 ALOGE("%s() no telephony Tx and/or RX device", __func__);
705 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100706 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100707 // createAudioPatchInternal now supports both HW / SW bridging
708 createRxPatch = true;
709 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100710 } else {
711 // If the RX device is on the primary HW module, then use legacy routing method for
712 // voice calls via setOutputDevice() on primary output.
713 // Otherwise, create two audio patches for TX and RX path.
714 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
715 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700716 // If the TX device is also on the primary HW module, setOutputDevice() will take care
717 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100718 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
719 (txSinkDevice != 0);
720 }
721 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
722 // Otherwise, create two audio patches for TX and RX path.
723 if (!createRxPatch) {
724 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700725 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200726 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800727 // If the TX device is on the primary HW module but RX device is
728 // on other HW module, SinkMetaData of telephony input should handle it
729 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700730 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700731 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100732 // terminate active capture if on the same HW module as the call TX source device
733 // FIXME: would be better to refine to only inputs whose profile connects to the
734 // call TX device but this information is not in the audio patch and logic here must be
735 // symmetric to the one in startInput()
736 for (const auto& activeDesc : mInputs.getActiveInputs()) {
737 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
738 closeActiveClients(activeDesc);
739 }
740 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200741 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800742 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100743 if (waitMs != nullptr) {
744 *waitMs = muteWaitMs;
745 }
746 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800747}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700748
Mikhail Naganov100f0122018-11-29 11:22:16 -0800749bool AudioPolicyManager::isDeviceOfModule(
750 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
751 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
752 if (module != 0) {
753 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
754 .indexOf(devDesc) != NAME_NOT_FOUND
755 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
756 .indexOf(devDesc) != NAME_NOT_FOUND;
757 }
758 return false;
759}
760
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200761void AudioPolicyManager::connectTelephonyRxAudioSource()
762{
Francois Gaffie601801d2021-06-22 13:27:39 +0200763 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200764 const struct audio_port_config source = {
765 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
766 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
767 };
768 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200769 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
770 ALOGE_IF(mCallRxSourceClient == nullptr,
771 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200772}
773
Francois Gaffie601801d2021-06-22 13:27:39 +0200774void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200775{
Francois Gaffie601801d2021-06-22 13:27:39 +0200776 if (clientDesc == nullptr) {
777 return;
778 }
779 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
780 "%s error stopping audio source", __func__);
781 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200782}
783
784void AudioPolicyManager::connectTelephonyTxAudioSource(
785 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
786 uint32_t delayMs)
787{
Francois Gaffie601801d2021-06-22 13:27:39 +0200788 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200789 if (srcDevice == nullptr || sinkDevice == nullptr) {
790 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
791 return;
792 }
793 PatchBuilder patchBuilder;
794 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
795 ALOGV("%s between source %s and sink %s", __func__,
796 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200797 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200798 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
799
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200800 struct audio_port_config source = {};
801 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200802 mCallTxSourceClient = new InternalSourceClientDescriptor(
803 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200804 mCommunnicationStrategy, toVolumeSource(aa));
805 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
806 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200807 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
808 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200809 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
810 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200811 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200812 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200813}
814
Eric Laurente0720872014-03-11 09:30:41 -0700815void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700816{
817 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100818 // store previous phone state for management of sonification strategy below
819 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100820 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100821
822 if (mEngine->setPhoneState(state) != NO_ERROR) {
823 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700824 return;
825 }
François Gaffie2110e042015-03-24 08:41:51 +0100826 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700827 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700828 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700829 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800830 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700831 }
832
François Gaffie2110e042015-03-24 08:41:51 +0100833 /**
834 * Switching to or from incall state or switching between telephony and VoIP lead to force
835 * routing command.
836 */
Eric Laurent74b71512019-11-06 17:21:57 -0800837 bool force = ((isStateInCall(oldState) != isStateInCall(state))
838 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700839
840 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700841 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700842
Eric Laurente552edb2014-03-10 17:42:56 -0700843 int delayMs = 0;
844 if (isStateInCall(state)) {
845 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100846 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
847 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700848 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700849 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700850 // mute media and sonification strategies and delay device switch by the largest
851 // latency of any output where either strategy is active.
852 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100853 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
854 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
855 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700856 (delayMs < (int)desc->latency()*2)) {
857 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700858 }
François Gaffiec005e562018-11-06 15:04:49 +0100859 setStrategyMute(musicStrategy, true, desc);
860 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
861 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
862 nullptr, true /*fromCache*/).types());
863 setStrategyMute(sonificationStrategy, true, desc);
864 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
865 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
866 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700867 }
868 }
869
Eric Laurent87ffa392015-05-22 10:32:38 -0700870 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700871 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100872 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700873 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100874 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
875 // force routing command to audio hardware when ending call
876 // even if no device change is needed
877 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
878 rxDevices = mPrimaryOutput->devices();
879 }
880 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200881 disconnectTelephonyAudioSource(mCallRxSourceClient);
882 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100883 }
François Gaffie11d30102018-11-02 16:09:09 +0100884 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700885 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700886 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700887
jiabin3ff8d7d2022-12-13 06:27:44 +0000888 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700889 // reevaluate routing on all outputs in case tracks have been started during the call
890 for (size_t i = 0; i < mOutputs.size(); i++) {
891 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100892 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200893 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
894 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000895 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
896 // If the device is using preferred mixer attributes, the output need to reopen
897 // with default configuration when the new selected devices are different from
898 // current routing devices.
899 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
900 continue;
901 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200902 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
903 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700904 }
905 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000906 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700907
Eric Laurent96d1dda2022-03-14 17:14:19 +0100908 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
909
Eric Laurente552edb2014-03-10 17:42:56 -0700910 if (isStateInCall(state)) {
911 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700912 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800913 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700914 }
915
916 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100917 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
918 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700919}
920
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700921audio_mode_t AudioPolicyManager::getPhoneState() {
922 return mEngine->getPhoneState();
923}
924
Eric Laurente0720872014-03-11 09:30:41 -0700925void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100926 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700927{
François Gaffie2110e042015-03-24 08:41:51 +0100928 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700929 if (config == mEngine->getForceUse(usage)) {
930 return;
931 }
Eric Laurente552edb2014-03-10 17:42:56 -0700932
François Gaffie2110e042015-03-24 08:41:51 +0100933 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
934 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
935 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700936 }
François Gaffie2110e042015-03-24 08:41:51 +0100937 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
938 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
939 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700940
941 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700942 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800943
Eric Laurent22fcda22019-05-17 16:28:47 -0700944 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
945 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800946 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700947 }
948
Eric Laurentdc462862016-07-19 12:29:53 -0700949 //FIXME: workaround for truncated touch sounds
950 // to be removed when the problem is handled by system UI
951 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700952 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
953 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
954 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700955
956 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100957 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700958}
959
Eric Laurente0720872014-03-11 09:30:41 -0700960void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700961{
962 ALOGV("setSystemProperty() property %s, value %s", property, value);
963}
964
Dorin Drimusecc9f422022-03-09 17:57:40 +0100965// Find an MSD output profile compatible with the parameters passed.
966// When "directOnly" is set, restrict search to profiles for direct outputs.
967sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
968 const DeviceVector& devices,
969 uint32_t samplingRate,
970 audio_format_t format,
971 audio_channel_mask_t channelMask,
972 audio_output_flags_t flags,
973 bool directOnly)
974{
975 flags = getRelevantFlags(flags, directOnly);
976
977 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
978 if (msdModule != nullptr) {
979 // for the msd module check if there are patches to the output devices
980 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
981 HwModuleCollection modules;
982 modules.add(msdModule);
983 return searchCompatibleProfileHwModules(
984 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
985 flags, directOnly);
986 }
987 }
988 return nullptr;
989}
990
Michael Chana94fbb22018-04-24 14:31:19 +1000991// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
992// search to profiles for direct outputs.
993sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100994 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000995 uint32_t samplingRate,
996 audio_format_t format,
997 audio_channel_mask_t channelMask,
998 audio_output_flags_t flags,
999 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001000{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001001 flags = getRelevantFlags(flags, directOnly);
1002
1003 return searchCompatibleProfileHwModules(
1004 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1005}
1006
1007audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1008 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001009 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001010 // only retain flags that will drive the direct output profile selection
1011 // if explicitly requested
1012 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001013 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001014 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1015 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001016 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001017 return flags;
1018}
Eric Laurent861a6282015-05-18 15:40:16 -07001019
Dorin Drimusecc9f422022-03-09 17:57:40 +01001020sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1021 const HwModuleCollection& hwModules,
1022 const DeviceVector& devices,
1023 uint32_t samplingRate,
1024 audio_format_t format,
1025 audio_channel_mask_t channelMask,
1026 audio_output_flags_t flags,
1027 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001028 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001029 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001030 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001031 if (!curProfile->isCompatibleProfile(devices,
1032 samplingRate, NULL /*updatedSamplingRate*/,
1033 format, NULL /*updatedFormat*/,
1034 channelMask, NULL /*updatedChannelMask*/,
1035 flags)) {
1036 continue;
1037 }
1038 // reject profiles not corresponding to a device currently available
1039 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1040 continue;
1041 }
1042 // reject profiles if connected device does not support codec
1043 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1044 continue;
1045 }
1046 if (!directOnly) {
1047 return curProfile;
1048 }
1049
1050 // when searching for direct outputs, if several profiles are compatible, give priority
1051 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001052 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001053 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001054 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001055 }
1056 profile = curProfile;
1057 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1058 break;
1059 }
Eric Laurente552edb2014-03-10 17:42:56 -07001060 }
1061 }
Eric Laurent861a6282015-05-18 15:40:16 -07001062 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001063}
1064
Eric Laurentfa0f6742021-08-17 18:39:44 +02001065sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001066 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001067{
1068 for (const auto& hwModule : mHwModules) {
1069 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001070 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001071 continue;
1072 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001073 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001074 // reject profiles not corresponding to a device currently available
1075 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1076 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1077 continue;
1078 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001079 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1080 != devices.size()) {
1081 continue;
1082 }
1083 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001084 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1085 return curProfile;
1086 }
1087 }
1088 return nullptr;
1089}
1090
Eric Laurentf4e63452017-11-06 19:31:46 +00001091audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001092{
François Gaffiec005e562018-11-06 15:04:49 +01001093 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001094
1095 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1096 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1097 // format, flags, etc. This may result in some discrepancy for functions that utilize
1098 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1099 // and AudioSystem::getOutputSamplingRate().
1100
François Gaffie11d30102018-11-02 16:09:09 +01001101 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001102 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001103
François Gaffie11d30102018-11-02 16:09:09 +01001104 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1105 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001106 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001107}
1108
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001109status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1110 const audio_attributes_t *srcAttr,
1111 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001112{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001113 if (srcAttr != NULL) {
1114 if (!isValidAttributes(srcAttr)) {
1115 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1116 __func__,
1117 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1118 srcAttr->tags);
1119 return BAD_VALUE;
1120 }
1121 *dstAttr = *srcAttr;
1122 } else {
1123 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1124 ALOGE("%s: invalid stream type", __func__);
1125 return BAD_VALUE;
1126 }
François Gaffiec005e562018-11-06 15:04:49 +01001127 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001128 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001129
1130 // Only honor audibility enforced when required. The client will be
1131 // forced to reconnect if the forced usage changes.
1132 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001133 dstAttr->flags = static_cast<audio_flags_mask_t>(
1134 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001135 }
1136
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001137 return NO_ERROR;
1138}
1139
Kevin Rocard153f92d2018-12-18 18:33:28 -08001140status_t AudioPolicyManager::getOutputForAttrInt(
1141 audio_attributes_t *resultAttr,
1142 audio_io_handle_t *output,
1143 audio_session_t session,
1144 const audio_attributes_t *attr,
1145 audio_stream_type_t *stream,
1146 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001147 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001148 audio_output_flags_t *flags,
1149 audio_port_handle_t *selectedDeviceId,
1150 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001151 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001152 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001153 bool *isSpatialized,
1154 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001155{
François Gaffiec005e562018-11-06 15:04:49 +01001156 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001157 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001158 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001159 const sp<DeviceDescriptor> requestedDevice =
1160 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1161
Eric Laurent8a1095a2019-11-08 14:44:16 -08001162 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001163 *isSpatialized = false;
1164
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001165 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1166 if (status != NO_ERROR) {
1167 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001168 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001169 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001170 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001171 }
François Gaffiec005e562018-11-06 15:04:49 +01001172 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001173
François Gaffiec005e562018-11-06 15:04:49 +01001174 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1175 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001176
Oscar Azucena873d10f2023-01-12 18:34:42 -08001177 bool usePrimaryOutputFromPolicyMixes = false;
1178
Kevin Rocard153f92d2018-12-18 18:33:28 -08001179 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1180 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1181 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001182 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001183 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1184 .channel_mask = config->channel_mask,
1185 .format = config->format,
1186 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001187 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001188 mAvailableOutputDevices, requestedDevice, primaryMix,
1189 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001190 if (status != OK) {
1191 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001192 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001193
Kevin Rocard153f92d2018-12-18 18:33:28 -08001194 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001195 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1196 && !audio_is_linear_pcm(config->format)) {
1197 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001198 return BAD_VALUE;
1199 }
1200 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001201 sp<DeviceDescriptor> deviceDesc =
1202 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1203 primaryMix->mDeviceAddress,
1204 AUDIO_FORMAT_DEFAULT);
1205 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001206 bool tryDirectForFlags = policyDesc == nullptr ||
1207 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1208 // if a direct output can be opened to deliver the track's multi-channel content to the
1209 // output rather than being downmixed by the primary output, then use this direct
1210 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1211 // mix.
1212 bool tryDirectForChannelMask = policyDesc != nullptr
1213 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1214 audio_channel_count_from_out_mask(config->channel_mask));
1215 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001216 audio_io_handle_t newOutput;
1217 status = openDirectOutput(
1218 *stream, session, config,
1219 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1220 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001221 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001222 policyDesc = mOutputs.valueFor(newOutput);
1223 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001224 } else if (tryDirectForFlags) {
1225 policyDesc = nullptr;
1226 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001227 }
1228 if (policyDesc != nullptr) {
1229 policyDesc->mPolicyMix = primaryMix;
1230 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001231 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001232
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001233 ALOGV("getOutputForAttr() returns output %d", *output);
1234 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1235 *outputType = API_OUT_MIX_PLAYBACK;
1236 } else {
1237 *outputType = API_OUTPUT_LEGACY;
1238 }
1239 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001240 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001241 }
François Gaffiec005e562018-11-06 15:04:49 +01001242 // Virtual sources must always be dynamicaly or explicitly routed
1243 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1244 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1245 return BAD_VALUE;
1246 }
1247 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1248 // in order to let the choice of the order to future vendor engine
1249 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001250
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001251 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001252 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001253 }
1254
Nadav Barb2f18162018-07-18 13:01:53 +03001255 // Set incall music only if device was explicitly set, and fallback to the device which is
1256 // chosen by the engine if not.
1257 // FIXME: provide a more generic approach which is not device specific and move this back
1258 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001259 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001260 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001261 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001262 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001263 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001264 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001265 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001266 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001267 }
1268 }
1269
François Gaffiec005e562018-11-06 15:04:49 +01001270 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1271 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1272 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001273
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001274 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001275 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001276 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001277 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001278 ALOGV("%s() Using MSD devices %s instead of devices %s",
1279 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001280 } else {
1281 *output = AUDIO_IO_HANDLE_NONE;
1282 }
1283 }
1284 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001285 sp<PreferredMixerAttributesInfo> info = nullptr;
1286 if (outputDevices.size() == 1) {
1287 info = getPreferredMixerAttributesInfo(
1288 outputDevices.itemAt(0)->getId(),
1289 mEngine->getProductStrategyForAttributes(*resultAttr));
jiabin5eaf0962022-12-20 20:11:38 +00001290 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1291 // and it is currently active.
1292 if (info != nullptr && info->getUid() != uid &&
1293 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1294 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001295 info = nullptr;
1296 }
1297 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001298 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001299 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001300 // The client will be active if the client is currently preferred mixer owner and the
1301 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001302 *isBitPerfect = (info != nullptr
1303 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001304 && info->getUid() == uid
1305 && *output != AUDIO_IO_HANDLE_NONE
1306 // When bit-perfect output is selected for the preferred mixer attributes owner,
1307 // only need to consider the config matches.
1308 && mOutputs.valueFor(*output)->isConfigurationMatched(
1309 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001310 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001311 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001312 AudioProfileVector profiles;
1313 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1314 if (ret == NO_ERROR && !profiles.empty()) {
1315 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
1316 : *profiles[0]->getChannels().begin();
1317 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
1318 : *profiles[0]->getSampleRates().begin();
1319 config->format = profiles[0]->getFormat();
1320 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001321 return INVALID_OPERATION;
1322 }
Paul McLeanaa981192015-03-21 09:55:15 -07001323
François Gaffiec005e562018-11-06 15:04:49 +01001324 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001325 for (auto &outputDevice : outputDevices) {
1326 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1327 *selectedDeviceId = outputDevice->getId();
1328 break;
1329 }
1330 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001331
Eric Laurent8a1095a2019-11-08 14:44:16 -08001332 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1333 *outputType = API_OUTPUT_TELEPHONY_TX;
1334 } else {
1335 *outputType = API_OUTPUT_LEGACY;
1336 }
1337
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001338 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1339
1340 return NO_ERROR;
1341}
1342
1343status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1344 audio_io_handle_t *output,
1345 audio_session_t session,
1346 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001347 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001348 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001349 audio_output_flags_t *flags,
1350 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001351 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001352 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001353 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001354 bool *isSpatialized,
1355 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001356{
1357 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1358 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1359 return INVALID_OPERATION;
1360 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001361 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001362 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001363 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001364 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001365 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001366 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001367 const sp<DeviceDescriptor> requestedDevice =
1368 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1369
1370 // Prevent from storing invalid requested device id in clients
1371 const audio_port_handle_t sanitizedRequestedPortId =
1372 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1373 *selectedDeviceId = sanitizedRequestedPortId;
1374
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001375 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001376 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001377 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1378 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001379 if (status != NO_ERROR) {
1380 return status;
1381 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001382 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001383 if (secondaryOutputs != nullptr) {
1384 for (auto &secondaryMix : secondaryMixes) {
1385 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1386 if (outputDesc != nullptr &&
1387 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1388 secondaryOutputs->push_back(outputDesc->mIoHandle);
1389 weakSecondaryOutputDescs.push_back(outputDesc);
1390 }
1391 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001392 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001393
Eric Laurent8fc147b2018-07-22 19:13:55 -07001394 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001395 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001396 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001397 };
jiabin4ef93452019-09-10 14:29:54 -07001398 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001399
Eric Laurentc209fe42020-06-05 18:11:23 -07001400 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001401 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001402 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001403 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001404 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001405 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001406 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001407 std::move(weakSecondaryOutputDescs),
1408 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001409 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001410
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001411 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1412 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001413
Eric Laurente83b55d2014-11-14 10:06:21 -08001414 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001415}
1416
Eric Laurentc529cf62020-04-17 18:19:10 -07001417status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1418 audio_session_t session,
1419 const audio_config_t *config,
1420 audio_output_flags_t flags,
1421 const DeviceVector &devices,
1422 audio_io_handle_t *output) {
1423
1424 *output = AUDIO_IO_HANDLE_NONE;
1425
1426 // skip direct output selection if the request can obviously be attached to a mixed output
1427 // and not explicitly requested
1428 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1429 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1430 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1431 return NAME_NOT_FOUND;
1432 }
1433
1434 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1435 // This prevents creating an offloaded track and tearing it down immediately after start
1436 // when audioflinger detects there is an active non offloadable effect.
1437 // FIXME: We should check the audio session here but we do not have it in this context.
1438 // This may prevent offloading in rare situations where effects are left active by apps
1439 // in the background.
1440 sp<IOProfile> profile;
1441 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1442 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1443 profile = getProfileForOutput(
1444 devices, config->sample_rate, config->format, config->channel_mask,
1445 flags, true /* directOnly */);
1446 }
1447
1448 if (profile == nullptr) {
1449 return NAME_NOT_FOUND;
1450 }
1451
1452 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1453 for (size_t i = 0; i < mOutputs.size(); i++) {
1454 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1455 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1456 // reuse direct output if currently open by the same client
1457 // and configured with same parameters
1458 if ((config->sample_rate == desc->getSamplingRate()) &&
1459 (config->format == desc->getFormat()) &&
1460 (config->channel_mask == desc->getChannelMask()) &&
1461 (session == desc->mDirectClientSession)) {
1462 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001463 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001464 mOutputs.keyAt(i), session);
1465 *output = mOutputs.keyAt(i);
1466 return NO_ERROR;
1467 }
1468 }
1469 }
1470
1471 if (!profile->canOpenNewIo()) {
1472 return NAME_NOT_FOUND;
1473 }
1474
1475 sp<SwAudioOutputDescriptor> outputDesc =
1476 new SwAudioOutputDescriptor(profile, mpClientInterface);
1477
Michael Chan6fb34492020-12-08 15:44:49 +11001478 // An MSD patch may be using the only output stream that can service this request. Release
1479 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001480 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001481
Eric Laurentf1f22e72021-07-13 14:04:14 +02001482 status_t status =
1483 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001484
1485 // only accept an output with the requested parameters
1486 if (status != NO_ERROR ||
1487 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1488 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1489 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1490 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1491 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1492 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1493 config->channel_mask, outputDesc->getChannelMask());
1494 if (*output != AUDIO_IO_HANDLE_NONE) {
1495 outputDesc->close();
1496 }
1497 // fall back to mixer output if possible when the direct output could not be open
1498 if (audio_is_linear_pcm(config->format) &&
1499 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1500 return NAME_NOT_FOUND;
1501 }
1502 *output = AUDIO_IO_HANDLE_NONE;
1503 return BAD_VALUE;
1504 }
1505 outputDesc->mDirectOpenCount = 1;
1506 outputDesc->mDirectClientSession = session;
1507
1508 addOutput(*output, outputDesc);
1509 mPreviousOutputs = mOutputs;
1510 ALOGV("%s returns new direct output %d", __func__, *output);
1511 mpClientInterface->onAudioPortListUpdate();
1512 return NO_ERROR;
1513}
1514
François Gaffie11d30102018-11-02 16:09:09 +01001515audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1516 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001517 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001518 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001519 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001520 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001521 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001522 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001523 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001524{
Andy Hungc88b0642018-04-27 15:42:35 -07001525 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001526
jiabine375d412019-02-26 12:54:53 -08001527 // Discard haptic channel mask when forcing muting haptic channels.
1528 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001529 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1530 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001531
Eric Laurente552edb2014-03-10 17:42:56 -07001532 // open a direct output if required by specified parameters
1533 //force direct flag if offload flag is set: offloading implies a direct output stream
1534 // and all common behaviors are driven by checking only the direct flag
1535 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001536 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1537 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001538 }
Nadav Bar766fb022018-01-07 12:18:03 +02001539 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1540 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001541 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001542
1543 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1544
Eric Laurente83b55d2014-11-14 10:06:21 -08001545 // only allow deep buffering for music stream type
1546 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001547 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001548 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001549 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001550 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1551 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001552 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001553 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001554 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001555 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001556 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001557 audio_is_linear_pcm(config->format) &&
1558 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001559 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001560 AUDIO_OUTPUT_FLAG_DIRECT);
1561 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001562 }
Eric Laurente552edb2014-03-10 17:42:56 -07001563
Carter Hsua3abb402021-10-26 11:11:20 +08001564 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1565 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1566 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1567 }
1568
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001569 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001570 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001571 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001572 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001573 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001574 }
1575
Eric Laurentc529cf62020-04-17 18:19:10 -07001576 audio_config_t directConfig = *config;
1577 directConfig.channel_mask = channelMask;
1578 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1579 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001580 return output;
1581 }
1582
Eric Laurent14cbfca2016-03-17 09:42:16 -07001583 // A request for HW A/V sync cannot fallback to a mixed output because time
1584 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001585 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001586 return AUDIO_IO_HANDLE_NONE;
1587 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001588 // A request for Tuner cannot fallback to a mixed output
1589 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1590 return AUDIO_IO_HANDLE_NONE;
1591 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001592
Eric Laurente552edb2014-03-10 17:42:56 -07001593 // ignoring channel mask due to downmix capability in mixer
1594
1595 // open a non direct output
1596
1597 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001598 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001599 // get which output is suitable for the specified stream. The actual
1600 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001601 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001602 if (prefMixerConfigInfo != nullptr) {
1603 for (audio_io_handle_t outputHandle : outputs) {
1604 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1605 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1606 output = outputHandle;
1607 break;
1608 }
1609 }
1610 if (output == AUDIO_IO_HANDLE_NONE) {
1611 // No output open with the preferred profile. Open a new one.
1612 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1613 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1614 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1615 config.format = prefMixerConfigInfo->getConfigBase().format;
1616 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1617 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1618 &config, prefMixerConfigInfo->getFlags());
1619 if (preferredOutput == nullptr) {
1620 ALOGE("%s failed to open output with preferred mixer config", __func__);
1621 } else {
1622 output = preferredOutput->mIoHandle;
1623 }
1624 }
1625 } else {
1626 // at this stage we should ignore the DIRECT flag as no direct output could be
1627 // found earlier
1628 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1629 output = selectOutput(
1630 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1631 }
Eric Laurente552edb2014-03-10 17:42:56 -07001632 }
François Gaffie11d30102018-11-02 16:09:09 +01001633 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001634 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001635 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001636
Eric Laurente552edb2014-03-10 17:42:56 -07001637 return output;
1638}
1639
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001640sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001641 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1642 mAvailableInputDevices);
1643 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1644}
1645
1646DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1647 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1648 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001649}
1650
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001651const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001652 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001653 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1654 if (msdModule != 0) {
1655 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1656 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1657 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1658 const struct audio_port_config *source = &patch->mPatch.sources[j];
1659 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1660 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001661 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001662 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001663 }
1664 }
1665 }
1666 return msdPatches;
1667}
1668
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001669bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1670 ssize_t index = mAudioPatches.indexOfKey(handle);
1671 if (index < 0) {
1672 return false;
1673 }
1674 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1675 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1676 if (msdModule == nullptr) {
1677 return false;
1678 }
1679 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1680 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1681 return true;
1682 }
1683 index = getMsdOutputPatches().indexOfKey(handle);
1684 if (index < 0) {
1685 return false;
1686 }
1687 return true;
1688}
1689
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001690status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1691 const InputProfileCollection &inputProfiles,
1692 const OutputProfileCollection &outputProfiles,
1693 const sp<DeviceDescriptor> &sourceDevice,
1694 const sp<DeviceDescriptor> &sinkDevice,
1695 AudioProfileVector& sourceProfiles,
1696 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001697 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001698 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001699 return NO_INIT;
1700 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001701 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001702 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001703 return NO_INIT;
1704 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001705 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001706 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1707 inProfile->supportsDevice(sourceDevice)) {
1708 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001709 }
1710 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001711 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001712 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001713 outProfile->supportsDevice(sinkDevice)) {
1714 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001715 }
1716 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001717 return NO_ERROR;
1718}
1719
1720status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1721 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1722 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1723{
Dean Wheatley16809da2022-12-09 14:55:46 +11001724 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1725 static const std::vector<audio_format_t> formatsOrder = {{
1726 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1727 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1728 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1729 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1730 // preferred).
1731 std::vector<audio_channel_mask_t> masks = {{
1732 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1733 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1734 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1735 // insert index masks (higher counts most preferred) as preferred over position masks
1736 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1737 masks.insert(
1738 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1739 }
1740 return masks;
1741 }();
1742
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001743 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001744 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1745 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001746 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001747 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1748 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001749 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001750 }
1751 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1752 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1753 sinkConfig->format = bestSinkConfig.format;
1754 // For encoded streams force direct flag to prevent downstream mixing.
1755 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1756 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001757 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1758 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001759 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001760 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1761 // raw and IEC61937 framed streams.
1762 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1763 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1764 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001765 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1766 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001767 sourceConfig->channel_mask =
1768 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1769 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1770 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001771 sourceConfig->format = bestSinkConfig.format;
1772 // Copy input stream directly without any processing (e.g. resampling).
1773 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1774 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1775 if (hwAvSync) {
1776 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1777 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1778 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1779 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1780 }
1781 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1782 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1783 sinkConfig->config_mask |= config_mask;
1784 sourceConfig->config_mask |= config_mask;
1785 return NO_ERROR;
1786}
1787
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001788PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1789 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001790{
1791 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001792 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1793 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1794 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1795 if (deviceModule == nullptr) {
1796 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1797 return patchBuilder;
1798 }
1799 const InputProfileCollection inputProfiles = msdIsSource ?
1800 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1801 const OutputProfileCollection outputProfiles = msdIsSource ?
1802 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1803
1804 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1805 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1806 device : getMsdAudioOutDevices().itemAt(0);
1807 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1808
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001809 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1810 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001811 AudioProfileVector sourceProfiles;
1812 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001813 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1814 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001815 for (auto hwAvSync : { true, false }) {
1816 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1817 sourceProfiles, sinkProfiles) != NO_ERROR) {
1818 continue;
1819 }
1820 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1821 &sinkConfig) == NO_ERROR) {
1822 // Found a matching config. Re-create PatchBuilder with this config.
1823 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1824 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001825 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001826 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001827 " supporting PCM format conversion.", __func__);
1828 return patchBuilder;
1829}
1830
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001831status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001832 DeviceVector devices;
1833 if (outputDevices != nullptr && outputDevices->size() > 0) {
1834 devices.add(*outputDevices);
1835 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001836 // Use media strategy for unspecified output device. This should only
1837 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1838 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001839 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001840 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001841 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001842 }
Michael Chan6fb34492020-12-08 15:44:49 +11001843 std::vector<PatchBuilder> patchesToCreate;
1844 for (auto i = 0u; i < devices.size(); ++i) {
1845 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001846 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001847 }
1848 // Retain only the MSD patches associated with outputDevices request.
1849 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001850 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001851 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1852 auto retainedPatch = false;
1853 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1854 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1855 patchesToRemove.removeItemsAt(i);
1856 retainedPatch = true;
1857 break;
1858 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001859 }
Michael Chan6fb34492020-12-08 15:44:49 +11001860 if (retainedPatch) {
1861 it = patchesToCreate.erase(it);
1862 continue;
1863 }
1864 ++it;
1865 }
1866 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1867 return NO_ERROR;
1868 }
1869 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1870 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001871 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001872 }
Michael Chan6fb34492020-12-08 15:44:49 +11001873 status_t status = NO_ERROR;
1874 for (const auto &p : patchesToCreate) {
1875 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1876 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1877 char message[256];
1878 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1879 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1880 currStatus == NO_ERROR ? "Success" : "Error",
1881 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1882 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1883 if (currStatus == NO_ERROR) {
1884 ALOGD("%s", message);
1885 } else {
1886 ALOGE("%s", message);
1887 if (status == NO_ERROR) {
1888 status = currStatus;
1889 }
1890 }
1891 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001892 return status;
1893}
1894
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001895void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1896 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001897 for (size_t i = 0; i < msdPatches.size(); i++) {
1898 const auto& patch = msdPatches[i];
1899 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1900 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1901 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1902 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1903 releaseAudioPatch(patch->getHandle(), mUidCached);
1904 break;
1905 }
1906 }
1907 }
1908}
1909
Dorin Drimus94d94412022-02-02 09:05:02 +01001910bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1911 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1912 AudioPatchCollection msdPatches = getMsdOutputPatches();
1913 for (size_t i = 0; i < msdPatches.size(); i++) {
1914 const auto& patch = msdPatches[i];
1915 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1916 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1917 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1918 const auto& foundDevice = devicesToCheck.getDevice(
1919 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1920 if (foundDevice != nullptr) {
1921 devicesToCheck.remove(foundDevice);
1922 if (devicesToCheck.isEmpty()) {
1923 return true;
1924 }
1925 }
1926 }
1927 }
1928 }
1929 return false;
1930}
1931
Eric Laurente0720872014-03-11 09:30:41 -07001932audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001933 audio_output_flags_t flags,
1934 audio_format_t format,
1935 audio_channel_mask_t channelMask,
1936 uint32_t samplingRate,
1937 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001938{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001939 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1940 "%s called with format %#x", __func__, format);
1941
jiabinebb6af42020-06-09 17:31:17 -07001942 // Return the output that haptic-generating attached to when 1) session id is specified,
1943 // 2) haptic-generating effect exists for given session id and 3) the output that
1944 // haptic-generating effect attached to is in given outputs.
1945 if (sessionId != AUDIO_SESSION_NONE) {
1946 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1947 sessionId, FX_IID_HAPTICGENERATOR);
1948 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1949 return hapticGeneratingOutput;
1950 }
1951 }
1952
Eric Laurent16c66dd2019-05-01 17:54:10 -07001953 // Flags disqualifying an output: the match must happen before calling selectOutput()
1954 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1955 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1956
1957 // Flags expressing a functional request: must be honored in priority over
1958 // other criteria
1959 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1960 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001961 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1962 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001963 // Flags expressing a performance request: have lower priority than serving
1964 // requested sampling rate or channel mask
1965 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1966 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1967 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1968
1969 const audio_output_flags_t functionalFlags =
1970 (audio_output_flags_t)(flags & kFunctionalFlags);
1971 const audio_output_flags_t performanceFlags =
1972 (audio_output_flags_t)(flags & kPerformanceFlags);
1973
1974 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1975
Eric Laurente552edb2014-03-10 17:42:56 -07001976 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001977 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001978 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001979 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001980 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001981 // with tiebreak preferring the minimum number of extra functional flags
1982 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001983 // 3: the output supporting the exact channel mask
1984 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00001985 // 5: the output with the highest sampling rate if the requested sample rate is
1986 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001987 // 6: the output with the highest number of requested performance flags
1988 // 7: the output with the bit depth the closest to the requested one
1989 // 8: the primary output
1990 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001991
Eric Laurent16c66dd2019-05-01 17:54:10 -07001992 // matching criteria values in priority order for best matching output so far
1993 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001994
Eric Laurent16c66dd2019-05-01 17:54:10 -07001995 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1996 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1997 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001998
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001999 for (audio_io_handle_t output : outputs) {
2000 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002001 // matching criteria values in priority order for current output
2002 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002003
Eric Laurent16c66dd2019-05-01 17:54:10 -07002004 if (outputDesc->isDuplicated()) {
2005 continue;
2006 }
2007 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2008 continue;
2009 }
Eric Laurent8838a382014-09-08 16:44:28 -07002010
Eric Laurent16c66dd2019-05-01 17:54:10 -07002011 // If haptic channel is specified, use the haptic output if present.
2012 // When using haptic output, same audio format and sample rate are required.
2013 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002014 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002015 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2016 continue;
2017 }
2018 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002019 && format == outputDesc->getFormat()
2020 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002021 currentMatchCriteria[0] = outputHapticChannelCount;
2022 }
2023
2024 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002025 const int matchingFunctionalFlags =
2026 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2027 const int totalFunctionalFlags =
2028 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2029 // Prefer matching functional flags, but subtract unnecessary functional flags.
2030 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002031
2032 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002033 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2034 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002035 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2036 channelCount <= outputChannelCount) {
2037 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002038 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2039 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002040 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002041 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002042 currentMatchCriteria[3] = outputChannelCount;
2043 }
2044
2045 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002046 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002047 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002048 }
2049
2050 // performance flags match
2051 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2052
2053 // format match
2054 if (format != AUDIO_FORMAT_INVALID) {
2055 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002056 PolicyAudioPort::kFormatDistanceMax -
2057 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002058 }
2059
2060 // primary output match
2061 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2062
2063 // compare match criteria by priority then value
2064 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2065 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2066 bestMatchCriteria = currentMatchCriteria;
2067 bestOutput = output;
2068
2069 std::stringstream result;
2070 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2071 std::ostream_iterator<int>(result, " "));
2072 ALOGV("%s new bestOutput %d criteria %s",
2073 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002074 }
2075 }
2076
Eric Laurent16c66dd2019-05-01 17:54:10 -07002077 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002078}
2079
Eric Laurent8fc147b2018-07-22 19:13:55 -07002080status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002081{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002082 ALOGV("%s portId %d", __FUNCTION__, portId);
2083
2084 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2085 if (outputDesc == 0) {
2086 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002087 return BAD_VALUE;
2088 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002089 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002090
Eric Laurent8fc147b2018-07-22 19:13:55 -07002091 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002092 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002093
Eric Laurent733ce942017-12-07 12:18:25 -08002094 status_t status = outputDesc->start();
2095 if (status != NO_ERROR) {
2096 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002097 }
2098
Eric Laurent97ac8712018-07-27 18:59:02 -07002099 uint32_t delayMs;
2100 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002101
2102 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002103 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002104 if (status == DEAD_OBJECT) {
2105 sp<SwAudioOutputDescriptor> desc =
2106 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2107 if (desc == nullptr) {
2108 // This is not common, it may indicate something wrong with the HAL.
2109 ALOGE("%s unable to open output with default config", __func__);
2110 return status;
2111 }
2112 desc->mUsePreferredMixerAttributes = true;
2113 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002114 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002115 }
jiabina84c3d32022-12-02 18:59:55 +00002116
2117 // If the client is the first one active on preferred mixer parameters, reopen the output
2118 // if the current mixer parameters doesn't match the preferred one.
2119 if (outputDesc->devices().size() == 1) {
2120 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2121 outputDesc->devices()[0]->getId(), client->strategy());
2122 if (info != nullptr && info->getUid() == client->uid()) {
2123 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2124 info->getConfigBase(), info->getFlags())) {
2125 stopSource(outputDesc, client);
2126 outputDesc->stop();
2127 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2128 config.channel_mask = info->getConfigBase().channel_mask;
2129 config.sample_rate = info->getConfigBase().sample_rate;
2130 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002131 sp<SwAudioOutputDescriptor> desc =
2132 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2133 if (desc == nullptr) {
2134 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002135 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002136 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002137 // Intentionally return error to let the client side resending request for
2138 // creating and starting.
2139 return DEAD_OBJECT;
2140 }
2141 info->increaseActiveClient();
2142 }
2143 }
2144
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002145 if (client->hasPreferredDevice()) {
2146 // playback activity with preferred device impacts routing occurred, inform upper layers
2147 mpClientInterface->onRoutingUpdated();
2148 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002149 if (delayMs != 0) {
2150 usleep(delayMs * 1000);
2151 }
2152
2153 return status;
2154}
2155
Eric Laurent96d1dda2022-03-14 17:14:19 +01002156bool AudioPolicyManager::isLeUnicastActive() const {
2157 if (isInCall()) {
2158 return true;
2159 }
2160 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2161}
2162
2163bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2164 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2165 return false;
2166 }
2167 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2168 ALOGV("%s active %d", __func__, active);
2169 return active;
2170}
2171
Eric Laurent97ac8712018-07-27 18:59:02 -07002172status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2173 const sp<TrackClientDescriptor>& client,
2174 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002175{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002176 // cannot start playback of STREAM_TTS if any other output is being used
2177 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002178
2179 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002180 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002181 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002182 auto clientStrategy = client->strategy();
2183 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002184 if (stream == AUDIO_STREAM_TTS) {
2185 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002186 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002187 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002188 return INVALID_OPERATION;
2189 } else {
2190 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2191 }
2192 } else {
2193 // some playback other than beacon starts
2194 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2195 }
2196
Eric Laurent77305a62016-07-25 16:39:22 -07002197 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002198 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002199 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002200
François Gaffie11d30102018-11-02 16:09:09 +01002201 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002202 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002203 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002204 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002205 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002206 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002207 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002208 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002209 } else {
2210 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002211 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002212 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2213 AUDIO_FORMAT_DEFAULT);
2214 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2215 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002216 }
2217
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002218 // requiresMuteCheck is false when we can bypass mute strategy.
2219 // It covers a common case when there is no materially active audio
2220 // and muting would result in unnecessary delay and dropped audio.
2221 const uint32_t outputLatencyMs = outputDesc->latency();
2222 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002223 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002224
Eric Laurente552edb2014-03-10 17:42:56 -07002225 // increment usage count for this stream on the requested output:
2226 // NOTE that the usage count is the same for duplicated output and hardware output which is
2227 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002228 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002229
2230 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002231 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002232 // Preferred device may be exclusive, use only if no other active clients on this output
2233 devices = DeviceVector(
2234 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2235 } else {
2236 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2237 }
François Gaffie11d30102018-11-02 16:09:09 +01002238 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002239 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002240 }
2241 }
Eric Laurente552edb2014-03-10 17:42:56 -07002242
François Gaffiec005e562018-11-06 15:04:49 +01002243 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002244 selectOutputForMusicEffects();
2245 }
2246
François Gaffie1c878552018-11-22 16:53:21 +01002247 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002248 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002249 if (devices.isEmpty()) {
2250 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002251 }
François Gaffiec005e562018-11-06 15:04:49 +01002252 bool shouldWait =
2253 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2254 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2255 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002256 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002257 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002258 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002259 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002260 // An output has a shared device if
2261 // - managed by the same hw module
2262 // - supports the currently selected device
2263 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002264 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002265
Eric Laurent77305a62016-07-25 16:39:22 -07002266 // force a device change if any other output is:
2267 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002268 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002269 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002270 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002271 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002272 // change the device currently selected by the other output.
2273 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002274 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002275 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002276 force = true;
2277 }
2278 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002279 // a notification so that audio focus effect can propagate, or that a mute/unmute
2280 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002281 const uint32_t latencyMs = desc->latency();
2282 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2283
2284 if (shouldWait && isActive && (waitMs < latencyMs)) {
2285 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002286 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002287
2288 // Require mute check if another output is on a shared device
2289 // and currently active to have proper drain and avoid pops.
2290 // Note restoring AudioTracks onto this output needs to invoke
2291 // a volume ramp if there is no mute.
2292 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002293 }
2294 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002295
jiabin3ff8d7d2022-12-13 06:27:44 +00002296 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2297 // If the output is open with preferred mixer attributes, but the routed device is
2298 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2299 // changed.
2300 return DEAD_OBJECT;
2301 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002302 const uint32_t muteWaitMs =
jiabin3ff8d7d2022-12-13 06:27:44 +00002303 setOutputDevices(outputDesc, devices, force, 0, nullptr, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002304
Eric Laurente552edb2014-03-10 17:42:56 -07002305 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002306 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002307 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002308 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002309 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002310 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002311 outputDesc->useHwGain() /*force*/)) {
2312 // request AudioService to reinitialize the volume curves asynchronously
2313 ALOGE("checkAndSetVolume failed, requesting volume range init");
2314 mpClientInterface->onVolumeRangeInitRequest();
2315 };
Eric Laurente552edb2014-03-10 17:42:56 -07002316
2317 // update the outputs if starting an output with a stream that can affect notification
2318 // routing
2319 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002320
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002321 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002322 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002323 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002324 }
Eric Laurentdc462862016-07-19 12:29:53 -07002325
2326 if (waitMs > muteWaitMs) {
2327 *delayMs = waitMs - muteWaitMs;
2328 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002329
2330 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2331 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2332 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2333 // change occurs after the MixerThread starts and causes a stream volume
2334 // glitch.
2335 //
2336 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002337 }
Eric Laurentdc462862016-07-19 12:29:53 -07002338
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002339 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002340 mEngine->getForceUse(
2341 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002342 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002343 }
2344
Eric Laurent97ac8712018-07-27 18:59:02 -07002345 // Automatically enable the remote submix input when output is started on a re routing mix
2346 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002347 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2348 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002349 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2350 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2351 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002352 "remote-submix",
2353 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002354 }
2355
Eric Laurent96d1dda2022-03-14 17:14:19 +01002356 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2357
Eric Laurente552edb2014-03-10 17:42:56 -07002358 return NO_ERROR;
2359}
2360
Eric Laurent96d1dda2022-03-14 17:14:19 +01002361void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2362 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2363 bool isUnicastActive = isLeUnicastActive();
2364
2365 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002366 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002367 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2368 for (size_t i = 0; i < mOutputs.size(); i++) {
2369 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2370 if (desc != ignoredOutput && desc->isActive()
2371 && ((isUnicastActive &&
2372 !desc->devices().
2373 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2374 || (wasUnicastActive &&
2375 !desc->devices().getDevicesFromTypes(
2376 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2377 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2378 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002379 if (desc->mUsePreferredMixerAttributes && force) {
2380 // If the device is using preferred mixer attributes, the output need to reopen
2381 // with default configuration when the new selected devices are different from
2382 // current routing devices.
2383 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2384 continue;
2385 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002386 setOutputDevices(desc, newDevices, force, delayMs);
2387 // re-apply device specific volume if not done by setOutputDevice()
2388 if (!force) {
2389 applyStreamVolumes(desc, newDevices.types(), delayMs);
2390 }
2391 }
2392 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002393 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002394 }
2395}
2396
Eric Laurent8fc147b2018-07-22 19:13:55 -07002397status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002398{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002399 ALOGV("%s portId %d", __FUNCTION__, portId);
2400
2401 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2402 if (outputDesc == 0) {
2403 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002404 return BAD_VALUE;
2405 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002406 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002407
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002408 if (client->hasPreferredDevice(true)) {
2409 // playback activity with preferred device impacts routing occurred, inform upper layers
2410 mpClientInterface->onRoutingUpdated();
2411 }
2412
Eric Laurent97ac8712018-07-27 18:59:02 -07002413 ALOGV("stopOutput() output %d, stream %d, session %d",
2414 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002415
Eric Laurent97ac8712018-07-27 18:59:02 -07002416 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002417
Eric Laurent733ce942017-12-07 12:18:25 -08002418 if (status == NO_ERROR ) {
2419 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002420 } else {
2421 return status;
2422 }
2423
2424 if (outputDesc->devices().size() == 1) {
2425 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2426 outputDesc->devices()[0]->getId(), client->strategy());
2427 if (info != nullptr && info->getUid() == client->uid()) {
2428 info->decreaseActiveClient();
2429 if (info->getActiveClientCount() == 0) {
2430 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2431 }
2432 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002433 }
2434 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002435}
2436
Eric Laurent97ac8712018-07-27 18:59:02 -07002437status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2438 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002439{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002440 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002441 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002442 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002443 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002444
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002445 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2446
François Gaffie1c878552018-11-22 16:53:21 +01002447 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2448 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002449 // Automatically disable the remote submix input when output is stopped on a
2450 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002451 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002452 if (isSingleDeviceType(
2453 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002454 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002455 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002456 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2457 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002458 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002459 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002460 }
2461 }
2462 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002463 if (client->hasPreferredDevice(true) &&
2464 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002465 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002466 forceDeviceUpdate = true;
2467 }
2468
Eric Laurente552edb2014-03-10 17:42:56 -07002469 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002470 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002471
Eric Laurente552edb2014-03-10 17:42:56 -07002472 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002473 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002474 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002475 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002476
2477 // If the routing does not change, if an output is routed on a device using HwGain
2478 // (aka setAudioPortConfig) and there are still active clients following different
2479 // volume group(s), force reapply volume
2480 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2481 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2482
Eric Laurente552edb2014-03-10 17:42:56 -07002483 // delay the device switch by twice the latency because stopOutput() is executed when
2484 // the track stop() command is received and at that time the audio track buffer can
2485 // still contain data that needs to be drained. The latency only covers the audio HAL
2486 // and kernel buffers. Also the latency does not always include additional delay in the
2487 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002488 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2489 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002490
2491 // force restoring the device selection on other active outputs if it differs from the
2492 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002493 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002494 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002495 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002496 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002497 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002498 desc->isActive() &&
2499 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002500 (newDevices != desc->devices())) {
2501 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2502 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002503
jiabin3ff8d7d2022-12-13 06:27:44 +00002504 if (desc->mUsePreferredMixerAttributes && force) {
2505 // If the device is using preferred mixer attributes, the output need to
2506 // reopen with default configuration when the new selected devices are
2507 // different from current routing devices.
2508 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2509 continue;
2510 }
François Gaffie11d30102018-11-02 16:09:09 +01002511 setOutputDevices(desc, newDevices2, force, delayMs);
2512
Eric Laurent57de36c2016-09-28 16:59:11 -07002513 // re-apply device specific volume if not done by setOutputDevice()
2514 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002515 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002516 }
Eric Laurente552edb2014-03-10 17:42:56 -07002517 }
2518 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002519 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002520 // update the outputs if stopping one with a stream that can affect notification routing
2521 handleNotificationRoutingForStream(stream);
2522 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002523
2524 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2525 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002526 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002527 }
2528
François Gaffiec005e562018-11-06 15:04:49 +01002529 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002530 selectOutputForMusicEffects();
2531 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002532
2533 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2534
Eric Laurente552edb2014-03-10 17:42:56 -07002535 return NO_ERROR;
2536 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002537 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002538 return INVALID_OPERATION;
2539 }
2540}
2541
jiabinbce0c1d2020-10-05 11:20:18 -07002542bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002543{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002544 ALOGV("%s portId %d", __FUNCTION__, portId);
2545
2546 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2547 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002548 // If an output descriptor is closed due to a device routing change,
2549 // then there are race conditions with releaseOutput from tracks
2550 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2551 // destroyed shortly thereafter.
2552 //
2553 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002554 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002555 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002556 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002557
2558 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002559
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302560 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2561 if (outputDesc->isClientActive(client)) {
2562 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2563 stopOutput(portId);
2564 }
2565
Eric Laurent8fc147b2018-07-22 19:13:55 -07002566 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2567 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002568 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002569 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002570 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002571 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002572 if (--outputDesc->mDirectOpenCount == 0) {
2573 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002574 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002575 }
2576 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302577
Andy Hung39efb7a2018-09-26 15:39:28 -07002578 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002579 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2580 // The output is pending reopened to query dynamic profiles and
2581 // there is no active clients
2582 closeOutput(outputDesc->mIoHandle);
2583 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2584 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2585 if (newOutputDesc == nullptr) {
2586 ALOGE("%s failed to open output", __func__);
2587 }
2588 return true;
2589 }
2590 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002591}
2592
Eric Laurentcaf7f482014-11-25 17:50:47 -08002593status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2594 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002595 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002596 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002597 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002598 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002599 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002600 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002601 input_type_t *inputType,
2602 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002603{
François Gaffiec005e562018-11-06 15:04:49 +01002604 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002605 "flags %#x attributes=%s requested device ID %d",
2606 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2607 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002608
Eric Laurentad2e7b92017-09-14 20:06:42 -07002609 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002610 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002611 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002612 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002613 sp<AudioInputDescriptor> inputDesc;
2614 sp<RecordClientDescriptor> clientDesc;
2615 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002616 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002617 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002618
2619 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2620 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2621 return INVALID_OPERATION;
2622 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002623
Francois Gaffie716e1432019-01-14 16:58:59 +01002624 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2625 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002626 }
2627
Paul McLean466dc8e2015-04-17 13:15:36 -06002628 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002629 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002630 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002631
Eric Laurentad2e7b92017-09-14 20:06:42 -07002632 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2633 // possible
2634 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2635 *input != AUDIO_IO_HANDLE_NONE) {
2636 ssize_t index = mInputs.indexOfKey(*input);
2637 if (index < 0) {
2638 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2639 status = BAD_VALUE;
2640 goto error;
2641 }
2642 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002643 RecordClientVector clients = inputDesc->getClientsForSession(session);
2644 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002645 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2646 status = BAD_VALUE;
2647 goto error;
2648 }
2649 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2650 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002651 // corresponds to a new client and is only permitted from the same UID.
2652 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002653 if (clients.size() > 1) {
2654 for (const auto& client : clients) {
2655 // The client map is ordered by key values (portId) and portIds are allocated
2656 // incrementaly. So the first client in this list is the one opened by audio flinger
2657 // when the mmap stream is created and should be ignored as it does not correspond
2658 // to an actual client
2659 if (client == *clients.cbegin()) {
2660 continue;
2661 }
2662 if (uid != client->uid() && !client->isSilenced()) {
2663 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2664 uid, client->portId(), client->uid());
2665 status = INVALID_OPERATION;
2666 goto error;
2667 }
Eric Laurent331679c2018-04-16 17:03:16 -07002668 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002669 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002670 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002671 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002672
Eric Laurentfecbceb2021-02-09 14:46:43 +01002673 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002674 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002675 }
2676
2677 *input = AUDIO_IO_HANDLE_NONE;
2678 *inputType = API_INPUT_INVALID;
2679
Francois Gaffie716e1432019-01-14 16:58:59 +01002680 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002681 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002682 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002683 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002684 ALOGW("%s could not find input mix for attr %s",
2685 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002686 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002687 }
jiabinc1de2df2019-05-07 14:26:40 -07002688 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2689 String8(attr->tags + strlen("addr=")),
2690 AUDIO_FORMAT_DEFAULT);
2691 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002692 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002693 __func__, attributes.source, attributes.tags);
2694 status = BAD_VALUE;
2695 goto error;
2696 }
2697
Kevin Rocard25f9b052019-02-27 15:08:54 -08002698 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2699 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2700 } else {
2701 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2702 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002703 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002704 if (explicitRoutingDevice != nullptr) {
2705 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002706 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002707 // Prevent from storing invalid requested device id in clients
2708 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002709 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002710 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2711 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002712 }
François Gaffie11d30102018-11-02 16:09:09 +01002713 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002714 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002715 status = BAD_VALUE;
2716 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002717 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002718 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2719 *inputType = API_INPUT_MIX_CAPTURE;
2720 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002721 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2722 // there is an external policy, but this input is attached to a mix of recorders,
2723 // meaning it receives audio injected into the framework, so the recorder doesn't
2724 // know about it and is therefore considered "legacy"
2725 *inputType = API_INPUT_LEGACY;
2726 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002727 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002728 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002729 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002730 } else {
2731 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002732 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002733
Eric Laurent599c7582015-12-07 18:05:55 -08002734 }
2735
François Gaffiec005e562018-11-06 15:04:49 +01002736 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002737 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002738 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002739 AudioProfileVector profiles;
2740 status_t ret = getProfilesForDevices(
2741 DeviceVector(device), profiles, flags, true /*isInput*/);
2742 if (ret == NO_ERROR && !profiles.empty()) {
2743 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
2744 : *profiles[0]->getChannels().begin();
2745 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
2746 : *profiles[0]->getSampleRates().begin();
2747 config->format = profiles[0]->getFormat();
2748 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002749 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002750 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002751
Eric Laurent8f42ea12018-08-08 09:08:25 -07002752exit:
2753
François Gaffiec005e562018-11-06 15:04:49 +01002754 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2755 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002756
Francois Gaffie716e1432019-01-14 16:58:59 +01002757 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002758 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002759 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002760
Mikhail Naganov2996f672019-04-18 12:29:59 -07002761 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002762 requestedDeviceId, attributes.source, flags,
2763 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002764 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002765 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002766
2767 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2768 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002769
Eric Laurent599c7582015-12-07 18:05:55 -08002770 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002771
2772error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002773 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002774}
2775
2776
François Gaffie11d30102018-11-02 16:09:09 +01002777audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002778 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002779 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002780 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002781 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002782 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002783{
2784 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002785 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002786 bool isSoundTrigger = false;
2787
François Gaffiec005e562018-11-06 15:04:49 +01002788 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002789 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2790 if (index >= 0) {
2791 input = mSoundTriggerSessions.valueFor(session);
2792 isSoundTrigger = true;
2793 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2794 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2795 } else {
2796 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002797 }
François Gaffiec005e562018-11-06 15:04:49 +01002798 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002799 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002800 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002801 }
2802
Carter Hsua3abb402021-10-26 11:11:20 +08002803 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2804 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2805 }
2806
Eric Laurentfe231122017-11-17 17:48:06 -08002807 // sampling rate and flags may be updated by getInputProfile
2808 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2809 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002810 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002811 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002812 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002813 // find a compatible input profile (not necessarily identical in parameters)
2814 sp<IOProfile> profile = getInputProfile(
2815 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2816 if (profile == nullptr) {
2817 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002818 }
jiabin2fd710d2022-05-02 23:20:22 +00002819
Glenn Kasten05ddca52016-02-11 08:17:12 -08002820 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002821 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002822 if (samplingRate == 0) {
2823 samplingRate = profileSamplingRate;
2824 }
Eric Laurente552edb2014-03-10 17:42:56 -07002825
Eric Laurent322b4d22015-04-03 15:57:54 -07002826 if (profile->getModuleHandle() == 0) {
2827 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002828 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002829 }
2830
Eric Laurentec376dc2021-04-08 20:41:22 +02002831 // Reuse an already opened input if a client with the same session ID already exists
2832 // on that input
2833 for (size_t i = 0; i < mInputs.size(); i++) {
2834 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2835 if (desc->mProfile != profile) {
2836 continue;
2837 }
2838 RecordClientVector clients = desc->clientsList();
2839 for (const auto &client : clients) {
2840 if (session == client->session()) {
2841 return desc->mIoHandle;
2842 }
2843 }
2844 }
2845
Eric Laurent3974e3b2017-12-07 17:58:43 -08002846 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002847 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002848 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002849 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002850 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002851 continue;
2852 }
2853 // if sound trigger, reuse input if used by other sound trigger on same session
2854 // else
2855 // reuse input if active client app is not in IDLE state
2856 //
2857 RecordClientVector clients = desc->clientsList();
2858 bool doClose = false;
2859 for (const auto& client : clients) {
2860 if (isSoundTrigger != client->isSoundTrigger()) {
2861 continue;
2862 }
2863 if (client->isSoundTrigger()) {
2864 if (session == client->session()) {
2865 return desc->mIoHandle;
2866 }
2867 continue;
2868 }
2869 if (client->active() && client->appState() != APP_STATE_IDLE) {
2870 return desc->mIoHandle;
2871 }
2872 doClose = true;
2873 }
2874 if (doClose) {
2875 closeInput(desc->mIoHandle);
2876 } else {
2877 i++;
2878 }
2879 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002880 }
2881
Eric Laurentfe231122017-11-17 17:48:06 -08002882 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002883
Eric Laurentfe231122017-11-17 17:48:06 -08002884 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2885 lConfig.sample_rate = profileSamplingRate;
2886 lConfig.channel_mask = profileChannelMask;
2887 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002888
François Gaffie11d30102018-11-02 16:09:09 +01002889 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002890
2891 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002892 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002893 (profileSamplingRate != lConfig.sample_rate) ||
2894 !audio_formats_match(profileFormat, lConfig.format) ||
2895 (profileChannelMask != lConfig.channel_mask)) {
2896 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002897 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002898 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002899 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002900 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002901 }
Eric Laurent599c7582015-12-07 18:05:55 -08002902 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002903 }
2904
Eric Laurentc722f302014-12-10 11:21:49 -08002905 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002906
Eric Laurent599c7582015-12-07 18:05:55 -08002907 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002908 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002909
Eric Laurent599c7582015-12-07 18:05:55 -08002910 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002911}
2912
Eric Laurent4eb58f12018-12-07 16:41:02 -08002913status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002914{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002915 ALOGV("%s portId %d", __FUNCTION__, portId);
2916
2917 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2918 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002919 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002920 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002921 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002922 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002923 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002924 if (client->active()) {
2925 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2926 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002927 }
2928
Eric Laurent8f42ea12018-08-08 09:08:25 -07002929 audio_session_t session = client->session();
2930
Eric Laurent4eb58f12018-12-07 16:41:02 -08002931 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002932
Eric Laurent4eb58f12018-12-07 16:41:02 -08002933 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002934
Eric Laurent4eb58f12018-12-07 16:41:02 -08002935 status_t status = inputDesc->start();
2936 if (status != NO_ERROR) {
2937 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002938 }
Eric Laurente552edb2014-03-10 17:42:56 -07002939
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002940 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002941 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002942 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002943
Eric Laurent8f42ea12018-08-08 09:08:25 -07002944 // indicate active capture to sound trigger service if starting capture from a mic on
2945 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002946 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002947 if (device != nullptr) {
2948 status = setInputDevice(input, device, true /* force */);
2949 } else {
2950 ALOGW("%s no new input device can be found for descriptor %d",
2951 __FUNCTION__, inputDesc->getId());
2952 status = BAD_VALUE;
2953 }
Eric Laurente552edb2014-03-10 17:42:56 -07002954
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002955 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002956 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002957 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002958 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002959 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2960 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002961 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002962 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002963
François Gaffie11d30102018-11-02 16:09:09 +01002964 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2965 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002966 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002967 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002968 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002969
Eric Laurent8f42ea12018-08-08 09:08:25 -07002970 // automatically enable the remote submix output when input is started if not
2971 // used by a policy mix of type MIX_TYPE_RECORDERS
2972 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002973 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002974 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002975 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002976 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002977 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2978 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002979 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002980 if (address != "") {
2981 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2982 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002983 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002984 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002985 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002986 } else if (status != NO_ERROR) {
2987 // Restore client activity state.
2988 inputDesc->setClientActive(client, false);
2989 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002990 }
2991
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002992 ALOGV("%s input %d source = %d status = %d exit",
2993 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002994
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002995 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002996}
2997
Eric Laurent8fc147b2018-07-22 19:13:55 -07002998status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002999{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003000 ALOGV("%s portId %d", __FUNCTION__, portId);
3001
3002 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3003 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003004 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003005 return BAD_VALUE;
3006 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003007 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003008 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003009 if (!client->active()) {
3010 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003011 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003012 }
Carter Hsue6139d52021-07-08 10:30:20 +08003013 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003014 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003015
Eric Laurent8f42ea12018-08-08 09:08:25 -07003016 inputDesc->stop();
3017 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003018 auto current_source = inputDesc->source();
3019 setInputDevice(input, getNewInputDevice(inputDesc),
3020 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003021 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003022 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003023 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003024 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003025 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3026 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003027 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003028 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003029
3030 // automatically disable the remote submix output when input is stopped if not
3031 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003032 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003033 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003034 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003035 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003036 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3037 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003038 }
3039 if (address != "") {
3040 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3041 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003042 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003043 }
3044 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003045 resetInputDevice(input);
3046
3047 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3048 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003049 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3050 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003051 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003052 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003053 }
3054 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003055 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003056 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003057}
3058
Eric Laurent8fc147b2018-07-22 19:13:55 -07003059void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003060{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003061 ALOGV("%s portId %d", __FUNCTION__, portId);
3062
3063 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3064 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003065 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003066 return;
3067 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003068 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003069 audio_io_handle_t input = inputDesc->mIoHandle;
3070
Eric Laurent8f42ea12018-08-08 09:08:25 -07003071 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003072
Andy Hung39efb7a2018-09-26 15:39:28 -07003073 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08003074
Andy Hung39efb7a2018-09-26 15:39:28 -07003075 if (inputDesc->getClientCount() > 0) {
3076 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003077 return;
3078 }
3079
Eric Laurent05b90f82014-08-27 15:32:29 -07003080 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003081 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003082 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003083}
3084
Eric Laurent8f42ea12018-08-08 09:08:25 -07003085void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003086{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003087 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003088
3089 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003090 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003091 }
3092}
3093
Eric Laurent8f42ea12018-08-08 09:08:25 -07003094void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3095{
3096 stopInput(portId);
3097 releaseInput(portId);
3098}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003099
Eric Laurent0dd51852019-04-19 18:18:58 -07003100void AudioPolicyManager::checkCloseInputs() {
3101 // After connecting or disconnecting an input device, close input if:
3102 // - it has no client (was just opened to check profile) OR
3103 // - none of its supported devices are connected anymore OR
3104 // - one of its clients cannot be routed to one of its supported
3105 // devices anymore. Otherwise update device selection
3106 std::vector<audio_io_handle_t> inputsToClose;
3107 for (size_t i = 0; i < mInputs.size(); i++) {
3108 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3109 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003110 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003111 inputsToClose.push_back(mInputs.keyAt(i));
3112 } else {
3113 bool close = false;
3114 for (const auto& client : input->clientsList()) {
3115 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003116 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3117 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003118 if (!input->supportedDevices().contains(device)) {
3119 close = true;
3120 break;
3121 }
3122 }
3123 if (close) {
3124 inputsToClose.push_back(mInputs.keyAt(i));
3125 } else {
3126 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3127 }
3128 }
3129 }
3130
3131 for (const audio_io_handle_t handle : inputsToClose) {
3132 ALOGV("%s closing input %d", __func__, handle);
3133 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003134 }
Eric Laurentd4692962014-05-05 18:13:44 -07003135}
3136
François Gaffie251c7f02018-11-07 10:41:08 +01003137void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003138{
3139 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003140 if (indexMin < 0 || indexMax < 0) {
3141 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3142 return;
3143 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003144 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003145
3146 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003147 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3148 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003149 continue;
3150 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003151 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003152 }
Eric Laurente552edb2014-03-10 17:42:56 -07003153}
3154
Eric Laurente0720872014-03-11 09:30:41 -07003155status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003156 int index,
3157 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003158{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003159 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003160 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3161 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3162 return NO_ERROR;
3163 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003164 ALOGV("%s: stream %s attributes=%s", __func__,
3165 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003166 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003167}
3168
Eric Laurente0720872014-03-11 09:30:41 -07003169status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003170 int *index,
3171 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003172{
François Gaffiec005e562018-11-06 15:04:49 +01003173 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3174 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003175 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003176 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003177 deviceTypes = mEngine->getOutputDevicesForStream(
3178 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003179 }
jiabin9a3361e2019-10-01 09:38:30 -07003180 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003181}
3182
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003183status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003184 int index,
3185 audio_devices_t device)
3186{
3187 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003188 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3189 if (group == VOLUME_GROUP_NONE) {
3190 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003191 return BAD_VALUE;
3192 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003193 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003194 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003195 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003196 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003197 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3198 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3199 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3200 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003201 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3202
3203 status = setVolumeCurveIndex(index, device, curves);
3204 if (status != NO_ERROR) {
3205 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3206 return status;
3207 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003208
jiabin9a3361e2019-10-01 09:38:30 -07003209 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003210 auto curCurvAttrs = curves.getAttributes();
3211 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3212 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003213 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003214 } else if (!curves.getStreamTypes().empty()) {
3215 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003216 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003217 } else {
3218 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3219 return BAD_VALUE;
3220 }
jiabin9a3361e2019-10-01 09:38:30 -07003221 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3222 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003223
François Gaffiecfe17322018-11-07 13:41:29 +01003224 // update volume on all outputs and streams matching the following:
3225 // - The requested stream (or a stream matching for volume control) is active on the output
3226 // - The device (or devices) selected by the engine for this stream includes
3227 // the requested device
3228 // - For non default requested device, currently selected device on the output is either the
3229 // requested device or one of the devices selected by the engine for this stream
3230 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3231 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003232 for (size_t i = 0; i < mOutputs.size(); i++) {
3233 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003234 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003235
jiabin9a3361e2019-10-01 09:38:30 -07003236 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3237 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003238 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003239
3240 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003241 continue;
3242 }
3243 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3244 curDevices.find(device) == curDevices.end()) {
3245 continue;
3246 }
3247 bool applyVolume = false;
3248 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3249 curSrcDevices.insert(device);
3250 applyVolume = (curSrcDevices.find(
3251 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3252 } else {
3253 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3254 }
3255 if (!applyVolume) {
3256 continue; // next output
3257 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003258 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3259 // If a higher priority strategy is active, and the output is routed to a device with a
3260 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003261 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003262 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003263 // If the volume source is active with higher priority source, ensure at least Sw Muted
3264 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003265 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3266 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3267 false /*preferredDevice*/);
3268 if (activeClients.empty()) {
3269 continue;
3270 }
3271 bool isPreempted = false;
3272 bool isHigherPriority = productStrategy < strategy;
3273 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003274 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003275 ALOGV("%s: Strategy=%d (\nrequester:\n"
3276 " group %d, volumeGroup=%d attributes=%s)\n"
3277 " higher priority source active:\n"
3278 " volumeGroup=%d attributes=%s) \n"
3279 " on output %zu, bailing out", __func__, productStrategy,
3280 group, group, toString(attributes).c_str(),
3281 client->volumeSource(), toString(client->attributes()).c_str(), i);
3282 applyVolume = false;
3283 isPreempted = true;
3284 break;
3285 }
3286 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003287 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003288 applyVolume = true;
3289 }
3290 }
3291 if (isPreempted || applyVolume) {
3292 break;
3293 }
3294 }
3295 if (!applyVolume) {
3296 continue; // next output
3297 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003298 }
François Gaffieed91f582020-01-31 10:35:37 +01003299 //FIXME: workaround for truncated touch sounds
3300 // delayed volume change for system stream to be removed when the problem is
3301 // handled by system UI
3302 status_t volStatus = checkAndSetVolume(
3303 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003304 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003305 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3306 if (volStatus != NO_ERROR) {
3307 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003308 }
3309 }
François Gaffiecfe17322018-11-07 13:41:29 +01003310 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3311 return status;
3312}
3313
François Gaffieaaac0fd2018-11-22 17:56:39 +01003314status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003315 audio_devices_t device,
3316 IVolumeCurves &volumeCurves)
3317{
3318 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3319 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003320 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3321 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003322 (index > volumeCurves.getVolumeIndexMax())) {
3323 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3324 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3325 return BAD_VALUE;
3326 }
3327 if (!audio_is_output_device(device)) {
3328 return BAD_VALUE;
3329 }
3330
3331 // Force max volume if stream cannot be muted
3332 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3333
François Gaffieaaac0fd2018-11-22 17:56:39 +01003334 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003335 volumeCurves.addCurrentVolumeIndex(device, index);
3336 return NO_ERROR;
3337}
3338
3339status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3340 int &index,
3341 audio_devices_t device)
3342{
3343 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3344 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003345 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003346 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003347 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003348 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003349 }
jiabin9a3361e2019-10-01 09:38:30 -07003350 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003351}
3352
3353status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3354 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003355 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003356{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003357 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003358 return BAD_VALUE;
3359 }
jiabin9a3361e2019-10-01 09:38:30 -07003360 index = curves.getVolumeIndex(deviceTypes);
3361 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003362 return NO_ERROR;
3363}
3364
3365status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3366 int &index)
3367{
3368 index = getVolumeCurves(attr).getVolumeIndexMin();
3369 return NO_ERROR;
3370}
3371
3372status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3373 int &index)
3374{
3375 index = getVolumeCurves(attr).getVolumeIndexMax();
3376 return NO_ERROR;
3377}
3378
Eric Laurent36829f92017-04-07 19:04:42 -07003379audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003380{
3381 // select one output among several suitable for global effects.
3382 // The priority is as follows:
3383 // 1: An offloaded output. If the effect ends up not being offloadable,
3384 // AudioFlinger will invalidate the track and the offloaded output
3385 // will be closed causing the effect to be moved to a PCM output.
3386 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003387 // 3: The primary output
3388 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003389
François Gaffiec005e562018-11-06 15:04:49 +01003390 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3391 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003392 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003393
Eric Laurent36829f92017-04-07 19:04:42 -07003394 if (outputs.size() == 0) {
3395 return AUDIO_IO_HANDLE_NONE;
3396 }
Eric Laurente552edb2014-03-10 17:42:56 -07003397
Eric Laurent36829f92017-04-07 19:04:42 -07003398 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3399 bool activeOnly = true;
3400
3401 while (output == AUDIO_IO_HANDLE_NONE) {
3402 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3403 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3404 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3405
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003406 for (audio_io_handle_t output : outputs) {
3407 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003408 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003409 continue;
3410 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003411 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3412 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003413 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003414 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003415 }
3416 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003417 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003418 }
3419 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003420 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003421 }
3422 }
3423 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3424 output = outputOffloaded;
3425 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3426 output = outputDeepBuffer;
3427 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3428 output = outputPrimary;
3429 } else {
3430 output = outputs[0];
3431 }
3432 activeOnly = false;
3433 }
3434
3435 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003436 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003437 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3438 mMusicEffectOutput = output;
3439 }
3440
3441 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003442 return output;
3443}
3444
Eric Laurent36829f92017-04-07 19:04:42 -07003445audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3446{
3447 return selectOutputForMusicEffects();
3448}
3449
Eric Laurente0720872014-03-11 09:30:41 -07003450status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003451 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003452 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003453 int session,
3454 int id)
3455{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003456 if (session != AUDIO_SESSION_DEVICE) {
3457 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003458 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003459 index = mInputs.indexOfKey(io);
3460 if (index < 0) {
3461 ALOGW("registerEffect() unknown io %d", io);
3462 return INVALID_OPERATION;
3463 }
Eric Laurente552edb2014-03-10 17:42:56 -07003464 }
3465 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003466 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3467 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3468 || strategy == PRODUCT_STRATEGY_NONE));
3469 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003470}
3471
Eric Laurentc241b0d2018-11-28 09:08:49 -08003472status_t AudioPolicyManager::unregisterEffect(int id)
3473{
3474 if (mEffects.getEffect(id) == nullptr) {
3475 return INVALID_OPERATION;
3476 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003477 if (mEffects.isEffectEnabled(id)) {
3478 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3479 setEffectEnabled(id, false);
3480 }
3481 return mEffects.unregisterEffect(id);
3482}
3483
3484status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3485{
3486 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3487 if (effect == nullptr) {
3488 return INVALID_OPERATION;
3489 }
3490
3491 status_t status = mEffects.setEffectEnabled(id, enabled);
3492 if (status == NO_ERROR) {
3493 mInputs.trackEffectEnabled(effect, enabled);
3494 }
3495 return status;
3496}
3497
Eric Laurent6c796322019-04-09 14:13:17 -07003498
3499status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3500{
3501 mEffects.moveEffects(ids, io);
3502 return NO_ERROR;
3503}
3504
Eric Laurentc75307b2015-03-17 15:29:32 -07003505bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3506{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003507 auto vs = toVolumeSource(stream, false);
3508 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003509}
3510
3511bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3512{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003513 auto vs = toVolumeSource(stream, false);
3514 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003515}
3516
Eric Laurente0720872014-03-11 09:30:41 -07003517bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003518{
3519 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003520 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003521 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003522 return true;
3523 }
3524 }
3525 return false;
3526}
3527
Eric Laurent275e8e92014-11-30 15:14:47 -08003528// Register a list of custom mixes with their attributes and format.
3529// When a mix is registered, corresponding input and output profiles are
3530// added to the remote submix hw module. The profile contains only the
3531// parameters (sampling rate, format...) specified by the mix.
3532// The corresponding input remote submix device is also connected.
3533//
3534// When a remote submix device is connected, the address is checked to select the
3535// appropriate profile and the corresponding input or output stream is opened.
3536//
3537// When capture starts, getInputForAttr() will:
3538// - 1 look for a mix matching the address passed in attribtutes tags if any
3539// - 2 if none found, getDeviceForInputSource() will:
3540// - 2.1 look for a mix matching the attributes source
3541// - 2.2 if none found, default to device selection by policy rules
3542// At this time, the corresponding output remote submix device is also connected
3543// and active playback use cases can be transferred to this mix if needed when reconnecting
3544// after AudioTracks are invalidated
3545//
3546// When playback starts, getOutputForAttr() will:
3547// - 1 look for a mix matching the address passed in attribtutes tags if any
3548// - 2 if none found, look for a mix matching the attributes usage
3549// - 3 if none found, default to device and output selection by policy rules.
3550
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003551status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003552{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003553 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3554 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003555 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003556 sp<HwModule> rSubmixModule;
3557 // examine each mix's route type
3558 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003559 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003560 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3561 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3562 ALOGE("Unsupported Policy Mix %zu of %zu: "
3563 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3564 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003565 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003566 break;
3567 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003568 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3569 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003570 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003571 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3572 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003573 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003574 rSubmixModule = mHwModules.getModuleFromName(
3575 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3576 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003577 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003578 i);
3579 res = INVALID_OPERATION;
3580 break;
3581 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003582 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003583
Eric Laurent97ac8712018-07-27 18:59:02 -07003584 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003585 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003586 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003587 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003588 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3589 } else {
3590 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3591 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003592 }
François Gaffie036e1e92015-03-19 10:16:24 +01003593
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003594 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003595 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003596 res = INVALID_OPERATION;
3597 break;
3598 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003599 audio_config_t outputConfig = mix.mFormat;
3600 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003601 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3602 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003603 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3604 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003605 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003606 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003607 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003608 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003609
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003610 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003611 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3612 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3613 ALOGE("Failed to set remote submix device available, type %u, address %s",
3614 mix.mDeviceType, address.string());
3615 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003616 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003617 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3618 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003619 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003620 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003621 i, mixes.size(), type, address.string());
3622
3623 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3624 mix.mDeviceType, mix.mDeviceAddress,
3625 String8(), AUDIO_FORMAT_DEFAULT);
3626 if (device == nullptr) {
3627 res = INVALID_OPERATION;
3628 break;
3629 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003630
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003631 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003632 // First try to find an already opened output supporting the device
3633 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003634 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003635
Eric Laurentc529cf62020-04-17 18:19:10 -07003636 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003637 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003638 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3639 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003640 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003641 } else {
3642 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003643 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003644 }
3645 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003646 // If no output found, try to find a direct output profile supporting the device
3647 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3648 sp<HwModule> module = mHwModules[i];
3649 for (size_t j = 0;
3650 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3651 j++) {
3652 sp<IOProfile> profile = module->getOutputProfiles()[j];
3653 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3654 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3655 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3656 address.string());
3657 res = INVALID_OPERATION;
3658 } else {
3659 foundOutput = true;
3660 }
3661 }
3662 }
3663 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003664 if (res != NO_ERROR) {
3665 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003666 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003667 res = INVALID_OPERATION;
3668 break;
3669 } else if (!foundOutput) {
3670 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003671 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003672 res = INVALID_OPERATION;
3673 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003674 } else {
3675 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003676 }
Eric Laurentc722f302014-12-10 11:21:49 -08003677 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003678 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003679 if (res != NO_ERROR) {
3680 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003681 } else if (checkOutputs) {
3682 checkForDeviceAndOutputChanges();
3683 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003684 }
3685 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003686}
3687
3688status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3689{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003690 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003691 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003692 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003693 sp<HwModule> rSubmixModule;
3694 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003695 for (const auto& mix : mixes) {
3696 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003697
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003698 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003699 rSubmixModule = mHwModules.getModuleFromName(
3700 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3701 if (rSubmixModule == 0) {
3702 res = INVALID_OPERATION;
3703 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003704 }
3705 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003706
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003707 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003708
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003709 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003710 res = INVALID_OPERATION;
3711 continue;
3712 }
3713
Kevin Rocard04ed0462019-05-02 17:53:24 -07003714 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3715 if (getDeviceConnectionState(device, address.string()) ==
3716 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3717 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3718 address.string(), "remote-submix",
3719 AUDIO_FORMAT_DEFAULT);
3720 if (res != OK) {
3721 ALOGE("Error making RemoteSubmix device unavailable for mix "
3722 "with type %d, address %s", device, address.string());
3723 }
3724 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003725 }
jiabin5740f082019-08-19 15:08:30 -07003726 rSubmixModule->removeOutputProfile(address.c_str());
3727 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003728
Kevin Rocard153f92d2018-12-18 18:33:28 -08003729 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003730 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003731 res = INVALID_OPERATION;
3732 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003733 } else {
3734 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003735 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003736 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003737 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003738 if (res == NO_ERROR && checkOutputs) {
3739 checkForDeviceAndOutputChanges();
3740 updateCallAndOutputRouting();
3741 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003742 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003743}
3744
Mikhail Naganov100f0122018-11-29 11:22:16 -08003745void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3746{
3747 size_t i = 0;
3748 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3749 for (const auto& fmt : mManualSurroundFormats) {
3750 if (i++ != 0) dst->append(", ");
3751 std::string sfmt;
3752 FormatConverter::toString(fmt, sfmt);
3753 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3754 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3755 }
3756}
3757
Eric Laurentc529cf62020-04-17 18:19:10 -07003758// Returns true if all devices types match the predicate and are supported by one HW module
3759bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003760 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003761 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003762 const char *context,
3763 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003764 for (size_t i = 0; i < devices.size(); i++) {
3765 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003766 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003767 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003768 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003769 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003770 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003771 return false;
3772 }
3773 }
3774 return true;
3775}
3776
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003777status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003778 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003779 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003780 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3781 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003782 }
3783 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003784 if (res != NO_ERROR) {
3785 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3786 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003787 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003788
3789 checkForDeviceAndOutputChanges();
3790 updateCallAndOutputRouting();
3791
3792 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003793}
3794
3795status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3796 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003797 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3798 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003799 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003800 __FUNCTION__, uid);
3801 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003802 }
3803
Eric Laurentc529cf62020-04-17 18:19:10 -07003804 checkForDeviceAndOutputChanges();
3805 updateCallAndOutputRouting();
3806
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003807 return res;
3808}
3809
Eric Laurent2517af32020-11-25 15:31:27 +01003810
jiabin0a488932020-08-07 17:32:40 -07003811status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3812 device_role_t role,
3813 const AudioDeviceTypeAddrVector &devices) {
3814 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3815 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003816
Eric Laurentc529cf62020-04-17 18:19:10 -07003817 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003818 return BAD_VALUE;
3819 }
jiabin0a488932020-08-07 17:32:40 -07003820 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003821 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003822 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3823 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003824 return status;
3825 }
3826
3827 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003828
3829 bool forceVolumeReeval = false;
3830 // FIXME: workaround for truncated touch sounds
3831 // to be removed when the problem is handled by system UI
3832 uint32_t delayMs = 0;
3833 if (strategy == mCommunnicationStrategy) {
3834 forceVolumeReeval = true;
3835 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3836 updateInputRouting();
3837 }
3838 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003839
3840 return NO_ERROR;
3841}
3842
3843void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3844{
3845 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003846 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003847 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003848 // Only apply special touch sound delay once
3849 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003850 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003851 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003852 for (size_t i = 0; i < mOutputs.size(); i++) {
3853 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3854 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003855 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3856 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003857 // As done in setDeviceConnectionState, we could also fix default device issue by
3858 // preventing the force re-routing in case of default dev that distinguishes on address.
3859 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003860 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003861 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3862 // If the device is using preferred mixer attributes, the output need to reopen
3863 // with default configuration when the new selected devices are different from
3864 // current routing devices.
3865 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3866 continue;
3867 }
Francois Gaffie601801d2021-06-22 13:27:39 +02003868 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3869 true /*requiresMuteCheck*/,
3870 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003871 // Only apply special touch sound delay once
3872 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003873 }
3874 if (forceVolumeReeval && !newDevices.isEmpty()) {
3875 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3876 }
3877 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003878 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01003879 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003880}
3881
Eric Laurent2517af32020-11-25 15:31:27 +01003882void AudioPolicyManager::updateInputRouting() {
3883 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303884 // Skip for hotword recording as the input device switch
3885 // is handled within sound trigger HAL
3886 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3887 continue;
3888 }
Eric Laurent2517af32020-11-25 15:31:27 +01003889 auto newDevice = getNewInputDevice(activeDesc);
3890 // Force new input selection if the new device can not be reached via current input
3891 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3892 setInputDevice(activeDesc->mIoHandle, newDevice);
3893 } else {
3894 closeInput(activeDesc->mIoHandle);
3895 }
3896 }
3897}
3898
Paul Wang5d7cdb52022-11-22 09:45:06 +00003899status_t
3900AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3901 device_role_t role,
3902 const AudioDeviceTypeAddrVector &devices) {
3903 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3904 dumpAudioDeviceTypeAddrVector(devices).c_str());
3905
Eric Laurent78fedbf2023-03-09 14:40:44 +01003906 if (!areAllDevicesSupported(
3907 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00003908 return BAD_VALUE;
3909 }
3910 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
3911 if (status != NO_ERROR) {
3912 ALOGW("Engine could not remove devices %s for strategy %d role %d",
3913 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
3914 return status;
3915 }
3916
3917 checkForDeviceAndOutputChanges();
3918
3919 bool forceVolumeReeval = false;
3920 // TODO(b/263479999): workaround for truncated touch sounds
3921 // to be removed when the problem is handled by system UI
3922 uint32_t delayMs = 0;
3923 if (strategy == mCommunnicationStrategy) {
3924 forceVolumeReeval = true;
3925 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3926 updateInputRouting();
3927 }
3928 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
3929
3930 return NO_ERROR;
3931}
3932
3933status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
3934 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003935{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003936 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003937
Paul Wang5d7cdb52022-11-22 09:45:06 +00003938 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003939 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01003940 ALOGW_IF(status != NAME_NOT_FOUND,
3941 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01003942 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003943 return status;
3944 }
3945
3946 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003947
3948 bool forceVolumeReeval = false;
3949 // FIXME: workaround for truncated touch sounds
3950 // to be removed when the problem is handled by system UI
3951 uint32_t delayMs = 0;
3952 if (strategy == mCommunnicationStrategy) {
3953 forceVolumeReeval = true;
3954 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3955 updateInputRouting();
3956 }
3957 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003958
3959 return NO_ERROR;
3960}
3961
jiabin0a488932020-08-07 17:32:40 -07003962status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3963 device_role_t role,
3964 AudioDeviceTypeAddrVector &devices) {
3965 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003966}
3967
Jiabin Huang3b98d322020-09-03 17:54:16 +00003968status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3969 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3970 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3971 dumpAudioDeviceTypeAddrVector(devices).c_str());
3972
Mikhail Naganov55773032020-10-01 15:08:13 -07003973 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003974 return BAD_VALUE;
3975 }
3976 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3977 ALOGW_IF(status != NO_ERROR,
3978 "Engine could not set preferred devices %s for audio source %d role %d",
3979 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3980
3981 return status;
3982}
3983
3984status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3985 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3986 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3987 dumpAudioDeviceTypeAddrVector(devices).c_str());
3988
Mikhail Naganov55773032020-10-01 15:08:13 -07003989 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003990 return BAD_VALUE;
3991 }
3992 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3993 ALOGW_IF(status != NO_ERROR,
3994 "Engine could not add preferred devices %s for audio source %d role %d",
3995 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3996
Eric Laurent2517af32020-11-25 15:31:27 +01003997 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003998 return status;
3999}
4000
4001status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4002 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4003{
4004 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4005 dumpAudioDeviceTypeAddrVector(devices).c_str());
4006
Eric Laurent78fedbf2023-03-09 14:40:44 +01004007 if (!areAllDevicesSupported(
4008 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004009 return BAD_VALUE;
4010 }
4011
4012 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4013 audioSource, role, devices);
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 remove 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::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4023 device_role_t role) {
4024 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4025
4026 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004027 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004028 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004029 if (status == NO_ERROR) {
4030 updateInputRouting();
4031 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004032 return status;
4033}
4034
4035status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4036 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4037 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4038}
4039
Oscar Azucena90e77632019-11-27 17:12:28 -08004040status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004041 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004042 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004043 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4044 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004045 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004046 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4047 if (status != NO_ERROR) {
4048 ALOGE("%s() could not set device affinity for userId %d",
4049 __FUNCTION__, userId);
4050 return status;
4051 }
4052
4053 // reevaluate outputs for all devices
4054 checkForDeviceAndOutputChanges();
4055 updateCallAndOutputRouting();
4056
4057 return NO_ERROR;
4058}
4059
4060status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004061 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08004062 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4063 if (status != NO_ERROR) {
4064 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4065 __FUNCTION__, userId);
4066 return status;
4067 }
4068
4069 // reevaluate outputs for all devices
4070 checkForDeviceAndOutputChanges();
4071 updateCallAndOutputRouting();
4072
4073 return NO_ERROR;
4074}
4075
Andy Hungc29d82b2018-10-05 12:23:17 -07004076void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004077{
Andy Hungc29d82b2018-10-05 12:23:17 -07004078 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004079 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004080 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004081 std::string stateLiteral;
4082 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004083 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004084 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4085 "communications", "media", "record", "dock", "system",
4086 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4087 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4088 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004089 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4090 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4091 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4092 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4093 dst->append(" (MANUAL: ");
4094 dumpManualSurroundFormats(dst);
4095 dst->append(")");
4096 }
4097 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004098 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004099 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4100 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004101 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07004102 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01004103
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004104 dst->append("\n");
4105 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4106 dst->append("\n");
4107 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004108 mHwModulesAll.dump(dst);
4109 mOutputs.dump(dst);
4110 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004111 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004112 mAudioPatches.dump(dst);
4113 mPolicyMixes.dump(dst);
4114 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004115
Kevin Rocardb99cc752019-03-21 20:52:24 -07004116 dst->appendFormat(" AllowedCapturePolicies:\n");
4117 for (auto& policy : mAllowedCapturePolicies) {
4118 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4119 }
4120
jiabina84c3d32022-12-02 18:59:55 +00004121 dst->appendFormat(" Preferred mixer audio configuration:\n");
4122 for (const auto it : mPreferredMixerAttrInfos) {
4123 dst->appendFormat(" - device port id: %d\n", it.first);
4124 for (const auto preferredMixerInfoIt : it.second) {
4125 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4126 preferredMixerInfoIt.second->dump(dst);
4127 }
4128 }
4129
François Gaffiec005e562018-11-06 15:04:49 +01004130 dst->appendFormat("\nPolicy Engine dump:\n");
4131 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004132}
4133
4134status_t AudioPolicyManager::dump(int fd)
4135{
4136 String8 result;
4137 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07004138 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004139 return NO_ERROR;
4140}
4141
Kevin Rocardb99cc752019-03-21 20:52:24 -07004142status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4143{
4144 mAllowedCapturePolicies[uid] = capturePolicy;
4145 return NO_ERROR;
4146}
4147
Eric Laurente552edb2014-03-10 17:42:56 -07004148// This function checks for the parameters which can be offloaded.
4149// This can be enhanced depending on the capability of the DSP and policy
4150// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004151audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004152{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004153 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004154 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004155 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004156 offloadInfo.format,
4157 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4158 offloadInfo.has_video);
4159
jiabin2b9d5a12021-12-10 01:06:29 +00004160 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004161 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004162 }
4163
4164 // See if there is a profile to support this.
4165 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004166 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004167 offloadInfo.sample_rate,
4168 offloadInfo.format,
4169 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004170 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4171 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004172 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4173 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4174 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004175 if (profile == nullptr) {
4176 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4177 }
4178 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4179 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4180 }
4181 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004182}
4183
Michael Chana94fbb22018-04-24 14:31:19 +10004184bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4185 const audio_attributes_t& attributes) {
4186 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004187 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004188 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4189 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004190 config.sample_rate,
4191 config.format,
4192 config.channel_mask,
4193 output_flags,
4194 true /* directOnly */);
4195 ALOGV("%s() profile %sfound with name: %s, "
4196 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4197 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004198 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004199 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004200
4201 // also try the MSD module if compatible profile not found
4202 if (profile == nullptr) {
4203 profile = getMsdProfileForOutput(outputDevices,
4204 config.sample_rate,
4205 config.format,
4206 config.channel_mask,
4207 output_flags,
4208 true /* directOnly */);
4209 ALOGV("%s() MSD profile %sfound with name: %s, "
4210 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4211 __FUNCTION__, profile != 0 ? "" : "NOT ",
4212 (profile != 0 ? profile->getTagName().c_str() : "null"),
4213 config.sample_rate, config.format, config.channel_mask, output_flags);
4214 }
4215 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004216}
4217
jiabin2b9d5a12021-12-10 01:06:29 +00004218bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4219 bool durationIgnored) {
4220 if (mMasterMono) {
4221 return false; // no offloading if mono is set.
4222 }
4223
4224 // Check if offload has been disabled
4225 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4226 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4227 return false;
4228 }
4229
4230 // Check if stream type is music, then only allow offload as of now.
4231 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4232 {
4233 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4234 return false;
4235 }
4236
4237 //TODO: enable audio offloading with video when ready
4238 const bool allowOffloadWithVideo =
4239 property_get_bool("audio.offload.video", false /* default_value */);
4240 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4241 ALOGV("%s: has_video == true, returning false", __func__);
4242 return false;
4243 }
4244
4245 //If duration is less than minimum value defined in property, return false
4246 const int min_duration_secs = property_get_int32(
4247 "audio.offload.min.duration.secs", -1 /* default_value */);
4248 if (!durationIgnored) {
4249 if (min_duration_secs >= 0) {
4250 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4251 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4252 __func__, min_duration_secs);
4253 return false;
4254 }
4255 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4256 ALOGV("%s: Offload denied by duration < default min(=%u)",
4257 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4258 return false;
4259 }
4260 }
4261
4262 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4263 // creating an offloaded track and tearing it down immediately after start when audioflinger
4264 // detects there is an active non offloadable effect.
4265 // FIXME: We should check the audio session here but we do not have it in this context.
4266 // This may prevent offloading in rare situations where effects are left active by apps
4267 // in the background.
4268 if (mEffects.isNonOffloadableEffectEnabled()) {
4269 return false;
4270 }
4271
4272 return true;
4273}
4274
4275audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4276 const audio_config_t *config) {
4277 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4278 offloadInfo.format = config->format;
4279 offloadInfo.sample_rate = config->sample_rate;
4280 offloadInfo.channel_mask = config->channel_mask;
4281 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4282 offloadInfo.has_video = false;
4283 offloadInfo.is_streaming = false;
4284 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4285
4286 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4287 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4288 audio_flags_to_audio_output_flags(attr->flags, &flags);
4289 // only retain flags that will drive compressed offload or passthrough
4290 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4291 if (offloadPossible) {
4292 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4293 }
4294 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4295
Dorin Drimusfae3c642022-03-17 18:36:30 +01004296 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004297 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004298 DeviceVector outputDevices = engineOutputDevices;
4299 // the MSD module checks for different conditions and output devices
4300 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4301 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4302 continue;
4303 }
4304 outputDevices = getMsdAudioOutDevices();
4305 }
jiabin2b9d5a12021-12-10 01:06:29 +00004306 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004307 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004308 config->sample_rate, nullptr /*updatedSamplingRate*/,
4309 config->format, nullptr /*updatedFormat*/,
4310 config->channel_mask, nullptr /*updatedChannelMask*/,
4311 flags)) {
4312 continue;
4313 }
4314 // reject profiles not corresponding to a device currently available
4315 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4316 continue;
4317 }
4318 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4319 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004320 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004321 != AUDIO_DIRECT_NOT_SUPPORTED) {
4322 // Already reports offload gapless supported. No need to report offload support.
4323 continue;
4324 }
4325 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4326 != AUDIO_OUTPUT_FLAG_NONE) {
4327 // If offload gapless is reported, no need to report offload support.
4328 directMode = (audio_direct_mode_t) ((directMode &
4329 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4330 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4331 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004332 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004333 }
4334 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004335 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004336 }
4337 }
4338 }
4339 return directMode;
4340}
4341
Dorin Drimusf2196d82022-01-03 12:11:18 +01004342status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4343 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004344 if (mEffects.isNonOffloadableEffectEnabled()) {
4345 return OK;
4346 }
jiabinf1c73972022-04-14 16:28:52 -07004347 DeviceVector devices;
4348 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004349 if (status != OK) {
4350 return status;
4351 }
4352 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4353 if (devices.empty()) {
4354 return OK; // no output devices for the attributes
4355 }
jiabinf1c73972022-04-14 16:28:52 -07004356 return getProfilesForDevices(devices, audioProfilesVector,
4357 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004358}
4359
jiabina84c3d32022-12-02 18:59:55 +00004360status_t AudioPolicyManager::getSupportedMixerAttributes(
4361 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4362 ALOGV("%s, portId=%d", __func__, portId);
4363 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4364 if (deviceDescriptor == nullptr) {
4365 ALOGE("%s the requested device is currently unavailable", __func__);
4366 return BAD_VALUE;
4367 }
4368 for (const auto& hwModule : mHwModules) {
4369 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4370 if (curProfile->supportsDevice(deviceDescriptor)) {
4371 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4372 }
4373 }
4374 }
4375 return NO_ERROR;
4376}
4377
4378status_t AudioPolicyManager::setPreferredMixerAttributes(
4379 const audio_attributes_t *attr,
4380 audio_port_handle_t portId,
4381 uid_t uid,
4382 const audio_mixer_attributes_t *mixerAttributes) {
4383 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4384 "mixerBehavior=%d}, uid=%d, portId=%u",
4385 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4386 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4387 mixerAttributes->mixer_behavior, uid, portId);
4388 if (attr->usage != AUDIO_USAGE_MEDIA) {
4389 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4390 return BAD_VALUE;
4391 }
4392 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4393 if (deviceDescriptor == nullptr) {
4394 ALOGE("%s the requested device is currently unavailable", __func__);
4395 return BAD_VALUE;
4396 }
4397 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4398 ALOGE("%s(%d), type=%d, is not a usb output device",
4399 __func__, portId, deviceDescriptor->type());
4400 return BAD_VALUE;
4401 }
4402
4403 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4404 audio_flags_to_audio_output_flags(attr->flags, &flags);
4405 flags = (audio_output_flags_t) (flags |
4406 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4407 sp<IOProfile> profile = nullptr;
4408 DeviceVector devices(deviceDescriptor);
4409 for (const auto& hwModule : mHwModules) {
4410 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4411 if (curProfile->hasDynamicAudioProfile()
4412 && curProfile->isCompatibleProfile(devices,
4413 mixerAttributes->config.sample_rate,
4414 nullptr /*updatedSamplingRate*/,
4415 mixerAttributes->config.format,
4416 nullptr /*updatedFormat*/,
4417 mixerAttributes->config.channel_mask,
4418 nullptr /*updatedChannelMask*/,
4419 flags,
4420 false /*exactMatchRequiredForInputFlags*/)) {
4421 profile = curProfile;
4422 break;
4423 }
4424 }
4425 }
4426 if (profile == nullptr) {
4427 ALOGE("%s, there is no compatible profile found", __func__);
4428 return BAD_VALUE;
4429 }
4430
4431 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4432 sp<PreferredMixerAttributesInfo>::make(
4433 uid, portId, profile, flags, *mixerAttributes);
4434 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4435 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4436
4437 // If 1) there is any client from the preferred mixer configuration owner that is currently
4438 // active and matches the strategy and 2) current output is on the preferred device and the
4439 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4440 // configuration.
4441 std::vector<audio_io_handle_t> outputsToReopen;
4442 for (size_t i = 0; i < mOutputs.size(); i++) {
4443 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004444 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4445 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4446 output->mUsePreferredMixerAttributes = true;
4447 } else {
4448 for (const auto &client: output->getActiveClients()) {
4449 if (client->uid() == uid && client->strategy() == strategy) {
4450 client->setIsInvalid();
4451 outputsToReopen.push_back(output->mIoHandle);
4452 }
jiabina84c3d32022-12-02 18:59:55 +00004453 }
4454 }
4455 }
4456 }
4457 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4458 config.sample_rate = mixerAttributes->config.sample_rate;
4459 config.channel_mask = mixerAttributes->config.channel_mask;
4460 config.format = mixerAttributes->config.format;
4461 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004462 sp<SwAudioOutputDescriptor> desc =
4463 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4464 if (desc == nullptr) {
4465 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4466 continue;
4467 }
4468 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004469 }
4470
4471 return NO_ERROR;
4472}
4473
4474sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
4475 audio_port_handle_t devicePortId, product_strategy_t strategy) {
4476 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4477 if (it == mPreferredMixerAttrInfos.end()) {
4478 return nullptr;
4479 }
4480 auto mixerAttrInfoIt = it->second.find(strategy);
4481 if (mixerAttrInfoIt == it->second.end()) {
4482 return nullptr;
4483 }
4484 return mixerAttrInfoIt->second;
4485}
4486
4487status_t AudioPolicyManager::getPreferredMixerAttributes(
4488 const audio_attributes_t *attr,
4489 audio_port_handle_t portId,
4490 audio_mixer_attributes_t* mixerAttributes) {
4491 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4492 portId, mEngine->getProductStrategyForAttributes(*attr));
4493 if (info == nullptr) {
4494 return NAME_NOT_FOUND;
4495 }
4496 *mixerAttributes = info->getMixerAttributes();
4497 return NO_ERROR;
4498}
4499
4500status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4501 audio_port_handle_t portId,
4502 uid_t uid) {
4503 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4504 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4505 if (preferredMixerAttrInfo == nullptr) {
4506 return NAME_NOT_FOUND;
4507 }
4508 if (preferredMixerAttrInfo->getUid() != uid) {
4509 ALOGE("%s, requested uid=%d, owned uid=%d",
4510 __func__, uid, preferredMixerAttrInfo->getUid());
4511 return PERMISSION_DENIED;
4512 }
4513 mPreferredMixerAttrInfos[portId].erase(strategy);
4514 if (mPreferredMixerAttrInfos[portId].empty()) {
4515 mPreferredMixerAttrInfos.erase(portId);
4516 }
4517
4518 // Reconfig existing output
4519 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4520 for (size_t i = 0; i < mOutputs.size(); i++) {
4521 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4522 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4523 }
4524 }
4525 for (const auto output : potentialOutputsToReopen) {
4526 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4527 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4528 preferredMixerAttrInfo->getFlags())) {
4529 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4530 }
4531 }
4532 return NO_ERROR;
4533}
4534
Eric Laurent6a94d692014-05-20 11:18:06 -07004535status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4536 audio_port_type_t type,
4537 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004538 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004539 unsigned int *generation)
4540{
jiabin19cdba52020-11-24 11:28:58 -08004541 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4542 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004543 return BAD_VALUE;
4544 }
4545 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004546 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004547 *num_ports = 0;
4548 }
4549
4550 size_t portsWritten = 0;
4551 size_t portsMax = *num_ports;
4552 *num_ports = 0;
4553 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004554 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4555 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004556 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004557 for (const auto& dev : mAvailableOutputDevices) {
4558 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004559 continue;
4560 }
4561 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004562 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004563 }
4564 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004565 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004566 }
4567 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004568 for (const auto& dev : mAvailableInputDevices) {
4569 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004570 continue;
4571 }
4572 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004573 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004574 }
4575 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004576 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004577 }
4578 }
4579 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4580 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4581 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4582 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4583 }
4584 *num_ports += mInputs.size();
4585 }
4586 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004587 size_t numOutputs = 0;
4588 for (size_t i = 0; i < mOutputs.size(); i++) {
4589 if (!mOutputs[i]->isDuplicated()) {
4590 numOutputs++;
4591 if (portsWritten < portsMax) {
4592 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4593 }
4594 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004595 }
Eric Laurent84c70242014-06-23 08:46:27 -07004596 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004597 }
4598 }
jiabina84c3d32022-12-02 18:59:55 +00004599
Eric Laurent6a94d692014-05-20 11:18:06 -07004600 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004601 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004602 return NO_ERROR;
4603}
4604
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004605status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4606 std::vector<media::AudioPortFw>* _aidl_return) {
4607 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4608 audio_port_v7 port;
4609 dev->toAudioPort(&port);
4610 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4611 _aidl_return->push_back(std::move(aidlPort));
4612 return OK;
4613 };
4614
4615 for (const auto& module : mHwModulesAll) {
4616 for (const auto& dev : module->getDeclaredDevices()) {
4617 if (role == media::AudioPortRole::NONE ||
4618 ((role == media::AudioPortRole::SOURCE)
4619 == audio_is_input_device(dev->type()))) {
4620 RETURN_STATUS_IF_ERROR(pushPort(dev));
4621 }
4622 }
4623 }
4624 return OK;
4625}
4626
jiabin19cdba52020-11-24 11:28:58 -08004627status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004628{
Eric Laurent99fcae42018-05-17 16:59:18 -07004629 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4630 return BAD_VALUE;
4631 }
4632 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4633 if (dev != 0) {
4634 dev->toAudioPort(port);
4635 return NO_ERROR;
4636 }
4637 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4638 if (dev != 0) {
4639 dev->toAudioPort(port);
4640 return NO_ERROR;
4641 }
4642 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4643 if (out != 0) {
4644 out->toAudioPort(port);
4645 return NO_ERROR;
4646 }
4647 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4648 if (in != 0) {
4649 in->toAudioPort(port);
4650 return NO_ERROR;
4651 }
4652 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004653}
4654
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004655status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4656 audio_patch_handle_t *handle,
4657 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004658{
François Gaffieafd4cea2019-11-18 15:50:22 +01004659 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004660 if (handle == NULL || patch == NULL) {
4661 return BAD_VALUE;
4662 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004663 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004664 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004665 return BAD_VALUE;
4666 }
4667 // only one source per audio patch supported for now
4668 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004669 return INVALID_OPERATION;
4670 }
Eric Laurent874c42872014-08-08 15:13:39 -07004671 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004672 return INVALID_OPERATION;
4673 }
Eric Laurent874c42872014-08-08 15:13:39 -07004674 for (size_t i = 0; i < patch->num_sinks; i++) {
4675 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4676 return INVALID_OPERATION;
4677 }
4678 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004679
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004680 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4681 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4682 if (srcDevice == nullptr || sinkDevice == nullptr) {
4683 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4684 return BAD_VALUE;
4685 }
4686 ALOGV("%s between source %s and sink %s", __func__,
4687 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4688 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4689 // Default attributes, default volume priority, not to infer with non raw audio patches.
4690 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4691 const struct audio_port_config *source = &patch->sources[0];
4692 sp<SourceClientDescriptor> sourceDesc =
4693 new InternalSourceClientDescriptor(
4694 portId, uid, attributes, *source, srcDevice, sinkDevice,
4695 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4696
4697 status_t status =
4698 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4699
4700 if (status != NO_ERROR) {
4701 return INVALID_OPERATION;
4702 }
4703 mAudioSources.add(portId, sourceDesc);
4704 return NO_ERROR;
4705}
4706
4707status_t AudioPolicyManager::connectAudioSourceToSink(
4708 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4709 const struct audio_patch *patch,
4710 audio_patch_handle_t &handle,
4711 uid_t uid, uint32_t delayMs)
4712{
4713 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4714 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4715 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4716 return INVALID_OPERATION;
4717 }
4718 sourceDesc->connect(handle, sinkDevice);
4719 if (isMsdPatch(handle)) {
4720 return NO_ERROR;
4721 }
4722 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4723 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4724 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4725 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4726 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4727 goto FailurePatchAdded;
4728 }
4729 status = swOutput->start();
4730 if (status != NO_ERROR) {
4731 goto FailureSourceAdded;
4732 }
4733 swOutput->addClient(sourceDesc);
4734 status = startSource(swOutput, sourceDesc, &delayMs);
4735 if (status != NO_ERROR) {
4736 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4737 goto FailureSourceActive;
4738 }
4739 if (delayMs != 0) {
4740 usleep(delayMs * 1000);
4741 }
4742 return NO_ERROR;
4743
4744FailureSourceActive:
4745 swOutput->stop();
4746 releaseOutput(sourceDesc->portId());
4747FailureSourceAdded:
4748 sourceDesc->setSwOutput(nullptr);
4749FailurePatchAdded:
4750 releaseAudioPatchInternal(handle);
4751 return INVALID_OPERATION;
4752}
4753
4754status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4755 audio_patch_handle_t *handle,
4756 uid_t uid, uint32_t delayMs,
4757 const sp<SourceClientDescriptor>& sourceDesc)
4758{
4759 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004760 sp<AudioPatch> patchDesc;
4761 ssize_t index = mAudioPatches.indexOfKey(*handle);
4762
François Gaffieafd4cea2019-11-18 15:50:22 +01004763 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4764 patch->sources[0].role,
4765 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004766#if LOG_NDEBUG == 0
4767 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004768 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4769 patch->sinks[i].role,
4770 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004771 }
4772#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004773
4774 if (index >= 0) {
4775 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004776 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4777 __func__, mUidCached, patchDesc->getUid(), uid);
4778 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004779 return INVALID_OPERATION;
4780 }
4781 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004782 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004783 }
4784
4785 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004786 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004787 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004788 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004789 return BAD_VALUE;
4790 }
Eric Laurent84c70242014-06-23 08:46:27 -07004791 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4792 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004793 if (patchDesc != 0) {
4794 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004795 ALOGV("%s source id differs for patch current id %d new id %d",
4796 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004797 return BAD_VALUE;
4798 }
4799 }
Eric Laurent874c42872014-08-08 15:13:39 -07004800 DeviceVector devices;
4801 for (size_t i = 0; i < patch->num_sinks; i++) {
4802 // Only support mix to devices connection
4803 // TODO add support for mix to mix connection
4804 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004805 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004806 return INVALID_OPERATION;
4807 }
4808 sp<DeviceDescriptor> devDesc =
4809 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4810 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004811 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004812 return BAD_VALUE;
4813 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004814
François Gaffie11d30102018-11-02 16:09:09 +01004815 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004816 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004817 NULL, // updatedSamplingRate
4818 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004819 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004820 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004821 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004822 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004823 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004824 return INVALID_OPERATION;
4825 }
4826 devices.add(devDesc);
4827 }
4828 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004829 return INVALID_OPERATION;
4830 }
Eric Laurent874c42872014-08-08 15:13:39 -07004831
Eric Laurent6a94d692014-05-20 11:18:06 -07004832 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004833 ALOGV("%s setting device %s on output %d",
4834 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004835 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004836 index = mAudioPatches.indexOfKey(*handle);
4837 if (index >= 0) {
4838 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004839 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004840 }
4841 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004842 patchDesc->setUid(uid);
4843 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004844 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004845 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004846 return INVALID_OPERATION;
4847 }
4848 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4849 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4850 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004851 // only one sink supported when connecting an input device to a mix
4852 if (patch->num_sinks > 1) {
4853 return INVALID_OPERATION;
4854 }
François Gaffie53615e22015-03-19 09:24:12 +01004855 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004856 if (inputDesc == NULL) {
4857 return BAD_VALUE;
4858 }
4859 if (patchDesc != 0) {
4860 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4861 return BAD_VALUE;
4862 }
4863 }
François Gaffie11d30102018-11-02 16:09:09 +01004864 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004865 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004866 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004867 return BAD_VALUE;
4868 }
4869
François Gaffie11d30102018-11-02 16:09:09 +01004870 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004871 patch->sinks[0].sample_rate,
4872 NULL, /*updatedSampleRate*/
4873 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004874 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004875 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004876 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004877 // FIXME for the parameter type,
4878 // and the NONE
4879 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004880 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004881 return INVALID_OPERATION;
4882 }
4883 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004884 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004885 device->toString().c_str(), inputDesc->mIoHandle);
4886 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004887 index = mAudioPatches.indexOfKey(*handle);
4888 if (index >= 0) {
4889 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004890 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004891 }
4892 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004893 patchDesc->setUid(uid);
4894 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004895 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004896 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004897 return INVALID_OPERATION;
4898 }
4899 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4900 // device to device connection
4901 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004902 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004903 return BAD_VALUE;
4904 }
4905 }
François Gaffie11d30102018-11-02 16:09:09 +01004906 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004907 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004908 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004909 return BAD_VALUE;
4910 }
Eric Laurent874c42872014-08-08 15:13:39 -07004911
Eric Laurent6a94d692014-05-20 11:18:06 -07004912 //update source and sink with our own data as the data passed in the patch may
4913 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004914 PatchBuilder patchBuilder;
4915 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004916
4917 // if first sink is to MSD, establish single MSD patch
4918 if (getMsdAudioOutDevices().contains(
4919 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4920 ALOGV("%s patching to MSD", __FUNCTION__);
4921 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4922 goto installPatch;
4923 }
4924
François Gaffieafd4cea2019-11-18 15:50:22 +01004925 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4926 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004927
Eric Laurent874c42872014-08-08 15:13:39 -07004928 for (size_t i = 0; i < patch->num_sinks; i++) {
4929 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004930 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004931 return INVALID_OPERATION;
4932 }
François Gaffie11d30102018-11-02 16:09:09 +01004933 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004934 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004935 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004936 return BAD_VALUE;
4937 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004938 audio_port_config sinkPortConfig = {};
4939 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4940 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004941
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004942 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4943 // volume management purpose (tracking activity)
4944 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4945 // in config XML to reach the sink so that is can be declared as available.
4946 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004947 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004948 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004949 // take care of dynamic routing for SwOutput selection,
4950 audio_attributes_t attributes = sourceDesc->attributes();
4951 audio_stream_type_t stream = sourceDesc->stream();
4952 audio_attributes_t resultAttr;
4953 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4954 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02004955 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
4956 config.channel_mask =
4957 (audio_channel_mask_get_representation(sourceMask)
4958 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
4959 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004960 config.format = sourceDesc->config().format;
4961 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4962 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4963 bool isRequestedDeviceForExclusiveUse = false;
4964 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004965 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00004966 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004967 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4968 &stream, sourceDesc->uid(), &config, &flags,
4969 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00004970 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004971 if (output == AUDIO_IO_HANDLE_NONE) {
4972 ALOGV("%s no output for device %s",
4973 __FUNCTION__, sinkDevice->toString().c_str());
4974 return INVALID_OPERATION;
4975 }
4976 outputDesc = mOutputs.valueFor(output);
4977 if (outputDesc->isDuplicated()) {
4978 ALOGE("%s output is duplicated", __func__);
4979 return INVALID_OPERATION;
4980 }
François Gaffie7e39df22022-04-26 12:48:49 +02004981 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4982 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004983 } else {
4984 // Same for "raw patches" aka created from createAudioPatch API
4985 SortedVector<audio_io_handle_t> outputs =
4986 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4987 // if the sink device is reachable via an opened output stream, request to
4988 // go via this output stream by adding a second source to the patch
4989 // description
4990 output = selectOutput(outputs);
4991 if (output == AUDIO_IO_HANDLE_NONE) {
4992 ALOGE("%s no output available for internal patch sink", __func__);
4993 return INVALID_OPERATION;
4994 }
4995 outputDesc = mOutputs.valueFor(output);
4996 if (outputDesc->isDuplicated()) {
4997 ALOGV("%s output for device %s is duplicated",
4998 __func__, sinkDevice->toString().c_str());
4999 return INVALID_OPERATION;
5000 }
François Gaffie7e39df22022-04-26 12:48:49 +02005001 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005002 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005003 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005004 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005005 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005006 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005007 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5008 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005009 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5010 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005011 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005012 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005013 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005014 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005015 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005016 return INVALID_OPERATION;
5017 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005018 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005019 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005020 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005021 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005022 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005023 srcMixPortConfig.ext.mix.usecase.stream =
5024 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005025 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5026 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005027 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005028 }
Eric Laurent83b88082014-06-20 18:31:16 -07005029 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005030 }
5031 // TODO: check from routing capabilities in config file and other conflicting patches
5032
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005033installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005034 status_t status = installPatch(
5035 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005036 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005037 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005038 return INVALID_OPERATION;
5039 }
5040 } else {
5041 return BAD_VALUE;
5042 }
5043 } else {
5044 return BAD_VALUE;
5045 }
5046 return NO_ERROR;
5047}
5048
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005049status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005050{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005051 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005052 ssize_t index = mAudioPatches.indexOfKey(handle);
5053
5054 if (index < 0) {
5055 return BAD_VALUE;
5056 }
5057 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005058 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5059 __func__, mUidCached, patchDesc->getUid(), uid);
5060 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005061 return INVALID_OPERATION;
5062 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005063 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5064 for (size_t i = 0; i < mAudioSources.size(); i++) {
5065 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5066 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5067 portId = sourceDesc->portId();
5068 break;
5069 }
5070 }
5071 return portId != AUDIO_PORT_HANDLE_NONE ?
5072 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005073}
Eric Laurent6a94d692014-05-20 11:18:06 -07005074
François Gaffieafd4cea2019-11-18 15:50:22 +01005075status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005076 uint32_t delayMs,
5077 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005078{
5079 ALOGV("%s patch %d", __func__, handle);
5080 if (mAudioPatches.indexOfKey(handle) < 0) {
5081 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5082 return BAD_VALUE;
5083 }
5084 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005085 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005086 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005087 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005088 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005089 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005090 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005091 return BAD_VALUE;
5092 }
5093
François Gaffie11d30102018-11-02 16:09:09 +01005094 setOutputDevices(outputDesc,
5095 getNewOutputDevices(outputDesc, true /*fromCache*/),
5096 true,
5097 0,
5098 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005099 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5100 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005101 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005102 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005103 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005104 return BAD_VALUE;
5105 }
5106 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005107 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005108 true,
5109 NULL);
5110 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005111 status_t status =
5112 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5113 ALOGV("%s patch panel returned %d patchHandle %d",
5114 __func__, status, patchDesc->getAfHandle());
5115 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005116 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005117 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005118 // SW or HW Bridge
5119 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5120 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005121 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005122 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5123 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5124 outputDesc = sourceDesc->swOutput().promote();
5125 }
5126 if (outputDesc == nullptr) {
5127 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5128 // releaseOutput has already called closeOutput in case of direct output
5129 return NO_ERROR;
5130 }
François Gaffie7e39df22022-04-26 12:48:49 +02005131 patchHandle = outputDesc->getPatchHandle();
5132 // When a Sw bridge is released, the mixer used by this bridge will release its
5133 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
5134 // Reuse patch handle to force audio flinger removing initial mixer patch removal
5135 // updating hal patch handle (prevent leaks).
5136 // While using a HwBridge, force reconsidering device only if not reusing an existing
5137 // output and no more activity on output (will force to close).
5138 bool force = sourceDesc->useSwBridge() ||
5139 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
5140 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5141 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5142 // Reconsider device only for cases:
5143 // 1 / Active Output
5144 // 2 / Inactive Output previously hosting HwBridge
5145 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5146 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5147 sourceDesc->canCloseOutput();
5148 setOutputDevices(outputDesc,
5149 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5150 outputDesc->devices(),
5151 force,
5152 0,
5153 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005154 } else {
5155 return BAD_VALUE;
5156 }
5157 } else {
5158 return BAD_VALUE;
5159 }
5160 return NO_ERROR;
5161}
5162
5163status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5164 struct audio_patch *patches,
5165 unsigned int *generation)
5166{
François Gaffie53615e22015-03-19 09:24:12 +01005167 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005168 return BAD_VALUE;
5169 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005170 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005171 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005172}
5173
Eric Laurente1715a42014-05-20 11:30:42 -07005174status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005175{
Eric Laurente1715a42014-05-20 11:30:42 -07005176 ALOGV("setAudioPortConfig()");
5177
5178 if (config == NULL) {
5179 return BAD_VALUE;
5180 }
5181 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5182 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005183 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5184 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005185 }
5186
Eric Laurenta121f902014-06-03 13:32:54 -07005187 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005188 if (config->type == AUDIO_PORT_TYPE_MIX) {
5189 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005190 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005191 if (outputDesc == NULL) {
5192 return BAD_VALUE;
5193 }
Eric Laurent84c70242014-06-23 08:46:27 -07005194 ALOG_ASSERT(!outputDesc->isDuplicated(),
5195 "setAudioPortConfig() called on duplicated output %d",
5196 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005197 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005198 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005199 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005200 if (inputDesc == NULL) {
5201 return BAD_VALUE;
5202 }
Eric Laurenta121f902014-06-03 13:32:54 -07005203 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005204 } else {
5205 return BAD_VALUE;
5206 }
5207 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5208 sp<DeviceDescriptor> deviceDesc;
5209 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5210 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5211 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5212 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5213 } else {
5214 return BAD_VALUE;
5215 }
5216 if (deviceDesc == NULL) {
5217 return BAD_VALUE;
5218 }
Eric Laurenta121f902014-06-03 13:32:54 -07005219 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005220 } else {
5221 return BAD_VALUE;
5222 }
5223
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005224 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005225 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5226 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005227 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005228 audioPortConfig->toAudioPortConfig(&newConfig, config);
5229 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005230 }
Eric Laurenta121f902014-06-03 13:32:54 -07005231 if (status != NO_ERROR) {
5232 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005233 }
Eric Laurente1715a42014-05-20 11:30:42 -07005234
5235 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005236}
5237
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005238void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5239{
Eric Laurentd60560a2015-04-10 11:31:20 -07005240 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005241 clearAudioPatches(uid);
5242 clearSessionRoutes(uid);
5243}
5244
Eric Laurent6a94d692014-05-20 11:18:06 -07005245void AudioPolicyManager::clearAudioPatches(uid_t uid)
5246{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005247 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005248 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005249 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005250 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005251 }
5252 }
5253}
5254
François Gaffiec005e562018-11-06 15:04:49 +01005255void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005256{
François Gaffiec005e562018-11-06 15:04:49 +01005257 // Take the first attributes following the product strategy as it is used to retrieve the routed
5258 // device. All attributes wihin a strategy follows the same "routing strategy"
5259 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5260 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005261 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005262 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005263 for (size_t j = 0; j < mOutputs.size(); j++) {
5264 if (mOutputs.keyAt(j) == ouptutToSkip) {
5265 continue;
5266 }
5267 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005268 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005269 continue;
5270 }
5271 // If the default device for this strategy is on another output mix,
5272 // invalidate all tracks in this strategy to force re connection.
5273 // Otherwise select new device on the output mix.
5274 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005275 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005276 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005277 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5278 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5279 // If the device is using preferred mixer attributes, the output need to reopen
5280 // with default configuration when the new selected devices are different from
5281 // current routing devices.
5282 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5283 continue;
5284 }
5285 setOutputDevices(outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005286 }
5287 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005288 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005289}
5290
5291void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5292{
5293 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005294 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005295 for (size_t i = 0; i < mOutputs.size(); i++) {
5296 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005297 for (const auto& client : outputDesc->getClientIterable()) {
5298 if (client->hasPreferredDevice() && client->uid() == uid) {
5299 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005300 auto clientStrategy = client->strategy();
5301 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5302 end(affectedStrategies)) {
5303 continue;
5304 }
5305 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005306 }
5307 }
5308 }
5309 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005310 for (const auto& strategy : affectedStrategies) {
5311 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005312 }
5313
5314 // remove input routes associated with this uid
5315 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005316 for (size_t i = 0; i < mInputs.size(); i++) {
5317 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005318 for (const auto& client : inputDesc->getClientIterable()) {
5319 if (client->hasPreferredDevice() && client->uid() == uid) {
5320 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5321 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005322 }
5323 }
5324 }
5325 // reroute inputs if necessary
5326 SortedVector<audio_io_handle_t> inputsToClose;
5327 for (size_t i = 0; i < mInputs.size(); i++) {
5328 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005329 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005330 inputsToClose.add(inputDesc->mIoHandle);
5331 }
5332 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005333 for (const auto& input : inputsToClose) {
5334 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005335 }
5336}
5337
Eric Laurentd60560a2015-04-10 11:31:20 -07005338void AudioPolicyManager::clearAudioSources(uid_t uid)
5339{
5340 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005341 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5342 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005343 stopAudioSource(mAudioSources.keyAt(i));
5344 }
5345 }
5346}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005347
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005348status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5349 audio_io_handle_t *ioHandle,
5350 audio_devices_t *device)
5351{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005352 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5353 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005354 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005355 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5356 if (deviceDesc == nullptr) {
5357 return INVALID_OPERATION;
5358 }
5359 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005360
François Gaffiedf372692015-03-19 10:43:27 +01005361 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005362}
5363
Eric Laurentd60560a2015-04-10 11:31:20 -07005364status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005365 const audio_attributes_t *attributes,
5366 audio_port_handle_t *portId,
5367 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005368{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005369 ALOGV("%s", __FUNCTION__);
5370 *portId = AUDIO_PORT_HANDLE_NONE;
5371
5372 if (source == NULL || attributes == NULL || portId == NULL) {
5373 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5374 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005375 return BAD_VALUE;
5376 }
5377
Eric Laurentd60560a2015-04-10 11:31:20 -07005378 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5379 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005380 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5381 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005382 return INVALID_OPERATION;
5383 }
5384
François Gaffie11d30102018-11-02 16:09:09 +01005385 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005386 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005387 String8(source->ext.device.address),
5388 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005389 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005390 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005391 return BAD_VALUE;
5392 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005393
jiabin4ef93452019-09-10 14:29:54 -07005394 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005395
François Gaffieaaac0fd2018-11-22 17:56:39 +01005396 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005397 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005398 mEngine->getStreamTypeForAttributes(*attributes),
5399 mEngine->getProductStrategyForAttributes(*attributes),
5400 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005401
5402 status_t status = connectAudioSource(sourceDesc);
5403 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005404 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005405 }
5406 return status;
5407}
5408
Francois Gaffie601801d2021-06-22 13:27:39 +02005409sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5410 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5411{
5412 ALOGV("%s", __FUNCTION__);
5413 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5414
5415 status_t status = startAudioSource(source, attributes, &portId, uid);
5416 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5417 return mAudioSources.valueFor(portId);
5418}
5419
5420
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005421status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005422{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005423 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005424
5425 // make sure we only have one patch per source.
5426 disconnectAudioSource(sourceDesc);
5427
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005428 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005429 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5430 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5431 sourceDesc->srcDevice()->type(),
5432 String8(sourceDesc->srcDevice()->address().c_str()),
5433 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005434 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005435 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005436 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005437 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005438 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5439 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5440 return INVALID_OPERATION;
5441 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005442 PatchBuilder patchBuilder;
5443 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5444 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005445
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005446 return connectAudioSourceToSink(
5447 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005448}
5449
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005450status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005451{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005452 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5453 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005454 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005455 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005456 return BAD_VALUE;
5457 }
5458 status_t status = disconnectAudioSource(sourceDesc);
5459
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005460 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005461 return status;
5462}
5463
Andy Hung2ddee192015-12-18 17:34:44 -08005464status_t AudioPolicyManager::setMasterMono(bool mono)
5465{
5466 if (mMasterMono == mono) {
5467 return NO_ERROR;
5468 }
5469 mMasterMono = mono;
5470 // if enabling mono we close all offloaded devices, which will invalidate the
5471 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5472 // for recreating the new AudioTrack as non-offloaded PCM.
5473 //
5474 // If disabling mono, we leave all tracks as is: we don't know which clients
5475 // and tracks are able to be recreated as offloaded. The next "song" should
5476 // play back offloaded.
5477 if (mMasterMono) {
5478 Vector<audio_io_handle_t> offloaded;
5479 for (size_t i = 0; i < mOutputs.size(); ++i) {
5480 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5481 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5482 offloaded.push(desc->mIoHandle);
5483 }
5484 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005485 for (const auto& handle : offloaded) {
5486 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005487 }
5488 }
5489 // update master mono for all remaining outputs
5490 for (size_t i = 0; i < mOutputs.size(); ++i) {
5491 updateMono(mOutputs.keyAt(i));
5492 }
5493 return NO_ERROR;
5494}
5495
5496status_t AudioPolicyManager::getMasterMono(bool *mono)
5497{
5498 *mono = mMasterMono;
5499 return NO_ERROR;
5500}
5501
Eric Laurentac9cef52017-06-09 15:46:26 -07005502float AudioPolicyManager::getStreamVolumeDB(
5503 audio_stream_type_t stream, int index, audio_devices_t device)
5504{
jiabin9a3361e2019-10-01 09:38:30 -07005505 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005506}
5507
jiabin81772902018-04-02 17:52:27 -07005508status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5509 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005510 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005511{
Kriti Dang6537def2021-03-02 13:46:59 +01005512 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5513 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005514 return BAD_VALUE;
5515 }
Kriti Dang6537def2021-03-02 13:46:59 +01005516 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5517 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005518
5519 size_t formatsWritten = 0;
5520 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005521
Kriti Dang6537def2021-03-02 13:46:59 +01005522 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005523 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5524 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005525 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005526 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005527 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005528 bool formatEnabled = true;
5529 switch (forceUse) {
5530 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005531 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005532 break;
5533 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5534 formatEnabled = false;
5535 break;
5536 default: // AUTO or ALWAYS => true
5537 break;
jiabin81772902018-04-02 17:52:27 -07005538 }
5539 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5540 }
jiabin81772902018-04-02 17:52:27 -07005541 }
5542 return NO_ERROR;
5543}
5544
Kriti Dang6537def2021-03-02 13:46:59 +01005545status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5546 audio_format_t *surroundFormats) {
5547 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5548 return BAD_VALUE;
5549 }
5550 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5551 __func__, *numSurroundFormats, surroundFormats);
5552
5553 size_t formatsWritten = 0;
5554 size_t formatsMax = *numSurroundFormats;
5555 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5556
5557 // Return formats from all device profiles that have already been resolved by
5558 // checkOutputsForDevice().
5559 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5560 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5561 audio_devices_t deviceType = device->type();
5562 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5563 // returns formats reported by HDMI devices.
5564 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5565 continue;
5566 }
5567 // Formats reported by sink devices
5568 std::unordered_set<audio_format_t> formatset;
5569 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5570 formatset.insert(it->second.begin(), it->second.end());
5571 }
5572
5573 // Formats hard-coded in the in policy configuration file (if any).
5574 FormatVector encodedFormats = device->encodedFormats();
5575 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5576 // Filter the formats which are supported by the vendor hardware.
5577 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5578 if (mConfig.getSurroundFormats().count(*it) != 0) {
5579 formats.insert(*it);
5580 } else {
5581 for (const auto& pair : mConfig.getSurroundFormats()) {
5582 if (pair.second.count(*it) != 0) {
5583 formats.insert(pair.first);
5584 break;
5585 }
5586 }
5587 }
5588 }
5589 }
5590 *numSurroundFormats = formats.size();
5591 for (const auto& format: formats) {
5592 if (formatsWritten < formatsMax) {
5593 surroundFormats[formatsWritten++] = format;
5594 }
5595 }
5596 return NO_ERROR;
5597}
5598
jiabin81772902018-04-02 17:52:27 -07005599status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5600{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005601 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005602 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5603 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005604 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005605 return BAD_VALUE;
5606 }
5607
Mikhail Naganov100f0122018-11-29 11:22:16 -08005608 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5609 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005610 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005611 return INVALID_OPERATION;
5612 }
5613
Mikhail Naganov100f0122018-11-29 11:22:16 -08005614 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005615 return NO_ERROR;
5616 }
5617
Mikhail Naganov100f0122018-11-29 11:22:16 -08005618 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005619 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005620 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005621 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005622 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005623 }
5624 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005625 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005626 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005627 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005628 }
5629 }
5630
5631 sp<SwAudioOutputDescriptor> outputDesc;
5632 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005633 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5634 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005635 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5636 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005637 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005638 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005639 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5640 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5641 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005642 name.c_str(),
5643 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005644 if (status != NO_ERROR) {
5645 continue;
5646 }
5647 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5648 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5649 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005650 name.c_str(),
5651 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005652 profileUpdated |= (status == NO_ERROR);
5653 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005654 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005655 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005656 AUDIO_DEVICE_IN_HDMI);
5657 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5658 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005659 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005660 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005661 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5662 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5663 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005664 name.c_str(),
5665 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005666 if (status != NO_ERROR) {
5667 continue;
5668 }
5669 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5670 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5671 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005672 name.c_str(),
5673 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005674 profileUpdated |= (status == NO_ERROR);
5675 }
5676
jiabin81772902018-04-02 17:52:27 -07005677 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005678 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005679 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005680 }
5681
5682 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5683}
5684
Eric Laurent5ada82e2019-08-29 17:53:54 -07005685void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005686{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005687 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005688 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005689 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005690 }
5691}
5692
jiabin6012f912018-11-02 17:06:30 -07005693bool AudioPolicyManager::isHapticPlaybackSupported()
5694{
5695 for (const auto& hwModule : mHwModules) {
5696 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5697 for (const auto &outProfile : outputProfiles) {
5698 struct audio_port audioPort;
5699 outProfile->toAudioPort(&audioPort);
5700 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5701 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5702 return true;
5703 }
5704 }
5705 }
5706 }
5707 return false;
5708}
5709
Carter Hsu325a8eb2022-01-19 19:56:51 +08005710bool AudioPolicyManager::isUltrasoundSupported()
5711{
5712 bool hasUltrasoundOutput = false;
5713 bool hasUltrasoundInput = false;
5714 for (const auto& hwModule : mHwModules) {
5715 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5716 if (!hasUltrasoundOutput) {
5717 for (const auto &outProfile : outputProfiles) {
5718 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5719 hasUltrasoundOutput = true;
5720 break;
5721 }
5722 }
5723 }
5724
5725 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5726 if (!hasUltrasoundInput) {
5727 for (const auto &inputProfile : inputProfiles) {
5728 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5729 hasUltrasoundInput = true;
5730 break;
5731 }
5732 }
5733 }
5734
5735 if (hasUltrasoundOutput && hasUltrasoundInput)
5736 return true;
5737 }
5738 return false;
5739}
5740
Atneya Nair698f5ef2022-12-15 16:15:09 -08005741bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5742{
5743 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5744 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5745 for (const auto& hwModule : mHwModules) {
5746 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5747 for (const auto &inputProfile : inputProfiles) {
5748 if ((inputProfile->getFlags() & mask) == mask) {
5749 return true;
5750 }
5751 }
5752 }
5753 return false;
5754}
5755
Eric Laurent8340e672019-11-06 11:01:08 -08005756bool AudioPolicyManager::isCallScreenModeSupported()
5757{
5758 return getConfig().isCallScreenModeSupported();
5759}
5760
5761
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005762status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005763{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005764 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005765 if (!sourceDesc->isConnected()) {
5766 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5767 return NO_ERROR;
5768 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005769 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5770 if (swOutput != 0) {
5771 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005772 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005773 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005774 }
jiabinbce0c1d2020-10-05 11:20:18 -07005775 if (releaseOutput(sourceDesc->portId())) {
5776 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5777 // no need to release audio patch here but just return NO_ERROR.
5778 return NO_ERROR;
5779 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005780 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005781 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005782 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005783 // close Hwoutput and remove from mHwOutputs
5784 } else {
5785 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5786 }
5787 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005788 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005789 sourceDesc->disconnect();
5790 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005791}
5792
François Gaffiec005e562018-11-06 15:04:49 +01005793sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5794 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005795{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005796 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005797 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005798 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005799 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005800 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5801 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005802 source = sourceDesc;
5803 break;
5804 }
5805 }
5806 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005807}
5808
Eric Laurentb4f42a92022-01-17 17:37:31 +01005809bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005810 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005811 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005812{
5813 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5814 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005815 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005816 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005817 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5818 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5819 return false;
5820 }
5821 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5822 return false;
5823 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005824 }
5825
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005826 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005827 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005828 if (profile == nullptr) {
5829 return false;
5830 }
5831
5832 // The caller can have the audio config criteria ignored by either passing a null ptr or
5833 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005834 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005835 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005836
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005837 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005838 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005839 return false;
5840 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005841 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005842 return true;
5843}
5844
5845void AudioPolicyManager::checkVirtualizerClientRoutes() {
5846 std::set<audio_stream_type_t> streamsToInvalidate;
5847 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005848 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5849 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005850 audio_attributes_t attr = client->attributes();
5851 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5852 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5853 audio_config_base_t clientConfig = client->config();
5854 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005855 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005856 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005857 streamsToInvalidate.insert(client->stream());
5858 }
5859 }
5860 }
5861
jiabinc44b3462022-12-08 12:52:31 -08005862 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005863}
5864
Eric Laurente191d1b2022-04-15 11:59:25 +02005865
5866bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5867 const sp<SwAudioOutputDescriptor>& outputDesc) {
5868 if (outputDesc->isDuplicated()) {
5869 return false;
5870 }
5871 DeviceVector devices = outputDesc->supportedDevices();
5872 for (size_t i = 0; i < mOutputs.size(); i++) {
5873 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5874 if (desc == outputDesc || desc->isDuplicated()) {
5875 continue;
5876 }
5877 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5878 if (!sharedDevices.isEmpty()
5879 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5880 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5881 return false;
5882 }
5883 }
5884 return true;
5885}
5886
5887
Eric Laurentfa0f6742021-08-17 18:39:44 +02005888status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005889 const audio_attributes_t *attr,
5890 audio_io_handle_t *output) {
5891 *output = AUDIO_IO_HANDLE_NONE;
5892
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005893 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5894 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5895 audio_config_t *configPtr = nullptr;
5896 audio_config_t config;
5897 if (mixerConfig != nullptr) {
5898 config = audio_config_initializer(mixerConfig);
5899 configPtr = &config;
5900 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005901 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005902 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005903 return BAD_VALUE;
5904 }
5905
5906 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005907 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005908 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005909 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005910 return BAD_VALUE;
5911 }
5912
Eric Laurente191d1b2022-04-15 11:59:25 +02005913 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005914 for (size_t i = 0; i < mOutputs.size(); i++) {
5915 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005916 if (!desc->isDuplicated()
5917 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5918 spatializerOutputs.push_back(desc);
5919 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005920 }
5921 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005922 mSpatializerOutput.clear();
5923 bool outputsChanged = false;
5924 for (const auto& desc : spatializerOutputs) {
5925 if (desc->mProfile == profile
5926 && (configPtr == nullptr
5927 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5928 mSpatializerOutput = desc;
5929 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5930 } else {
5931 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5932 " and devices %s", __func__, desc->mIoHandle,
5933 configPtr != nullptr ? configPtr->channel_mask : 0,
5934 devices.toString().c_str());
5935 closeOutput(desc->mIoHandle);
5936 outputsChanged = true;
5937 }
Eric Laurent39095982021-08-24 18:29:27 +02005938 }
5939
Eric Laurente191d1b2022-04-15 11:59:25 +02005940 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005941 sp<SwAudioOutputDescriptor> desc =
5942 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005943 if (desc != nullptr) {
5944 mSpatializerOutput = desc;
5945 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005946 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005947 }
5948
5949 checkVirtualizerClientRoutes();
5950
Eric Laurente191d1b2022-04-15 11:59:25 +02005951 if (outputsChanged) {
5952 mPreviousOutputs = mOutputs;
5953 mpClientInterface->onAudioPortListUpdate();
5954 }
5955
5956 if (mSpatializerOutput == nullptr) {
5957 ALOGV("%s could not open spatializer output with requested config", __func__);
5958 return BAD_VALUE;
5959 }
Eric Laurent39095982021-08-24 18:29:27 +02005960 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005961 ALOGV("%s returning new spatializer output %d", __func__, *output);
5962 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005963}
5964
Eric Laurentfa0f6742021-08-17 18:39:44 +02005965status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5966 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005967 return INVALID_OPERATION;
5968 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005969 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005970 return BAD_VALUE;
5971 }
Eric Laurent39095982021-08-24 18:29:27 +02005972
Eric Laurente191d1b2022-04-15 11:59:25 +02005973 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5974 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5975 closeOutput(mSpatializerOutput->mIoHandle);
5976 //from now on mSpatializerOutput is null
5977 checkVirtualizerClientRoutes();
5978 }
Eric Laurent39095982021-08-24 18:29:27 +02005979
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005980 return NO_ERROR;
5981}
5982
Eric Laurente552edb2014-03-10 17:42:56 -07005983// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005984// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005985// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005986uint32_t AudioPolicyManager::nextAudioPortGeneration()
5987{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005988 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005989}
5990
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005991static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005992 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5993 !audioPolicyXmlConfigFile.empty()) {
5994 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5995 if (ret == NO_ERROR) {
5996 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005997 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005998 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005999 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07006000 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09006001}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09006002
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006003AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
6004 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07006005 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006006 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006007 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006008 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006009 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006010 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006011 mAudioPortGeneration(1),
6012 mBeaconMuteRefCount(0),
6013 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006014 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006015 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006016 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006017 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006018{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006019}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006020
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006021AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
6022 : AudioPolicyManager(clientInterface, false /*forTesting*/)
6023{
6024 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006025}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006026
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07006027void AudioPolicyManager::loadConfig() {
6028 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01006029 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006030 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01006031 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006032}
6033
6034status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07006035 {
6036 auto engLib = EngineLibrary::load(
6037 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
6038 if (!engLib) {
6039 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
6040 return NO_INIT;
6041 }
6042 mEngine = engLib->createEngine();
6043 if (mEngine == nullptr) {
6044 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
6045 return NO_INIT;
6046 }
François Gaffie2110e042015-03-24 08:41:51 +01006047 }
6048 mEngine->setObserver(this);
6049 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006050 if (status != NO_ERROR) {
6051 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6052 return status;
6053 }
François Gaffie2110e042015-03-24 08:41:51 +01006054
Mikhail Naganove93ae282023-02-02 15:28:26 -08006055 // If microphones address is empty, set it according to device type
6056 for (size_t i = 0; i < mInputDevicesAll.size(); i++) {
6057 if (mInputDevicesAll[i]->address().empty()) {
6058 if (mInputDevicesAll[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
6059 mInputDevicesAll[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
6060 } else if (mInputDevicesAll[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
6061 mInputDevicesAll[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
6062 }
6063 }
6064 }
6065
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006066 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006067 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6068 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6069
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006070 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006071 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006072 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006073
Eric Laurent3a4311c2014-03-17 12:00:47 -07006074 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01006075 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
6076 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
6077 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006078 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006079 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006080 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006081
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006082 // Silence ALOGV statements
6083 property_set("log.tag." LOG_TAG, "D");
6084
Eric Laurente552edb2014-03-10 17:42:56 -07006085 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006086 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006087}
6088
Eric Laurente0720872014-03-11 09:30:41 -07006089AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006090{
Eric Laurente552edb2014-03-10 17:42:56 -07006091 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006092 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006093 }
6094 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006095 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006096 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006097 mAvailableOutputDevices.clear();
6098 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006099 mOutputs.clear();
6100 mInputs.clear();
6101 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08006102 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006103 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006104}
6105
Eric Laurente0720872014-03-11 09:30:41 -07006106status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006107{
Eric Laurent87ffa392015-05-22 10:32:38 -07006108 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006109}
6110
Eric Laurente552edb2014-03-10 17:42:56 -07006111// ---
6112
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006113void AudioPolicyManager::onNewAudioModulesAvailable()
6114{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006115 DeviceVector newDevices;
6116 onNewAudioModulesAvailableInt(&newDevices);
6117 if (!newDevices.empty()) {
6118 nextAudioPortGeneration();
6119 mpClientInterface->onAudioPortListUpdate();
6120 }
6121}
6122
6123void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6124{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006125 for (const auto& hwModule : mHwModulesAll) {
6126 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6127 continue;
6128 }
6129 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
6130 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
6131 ALOGW("could not open HW module %s", hwModule->getName());
6132 continue;
6133 }
6134 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006135 // open all output streams needed to access attached devices.
6136 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006137 // This also validates mAvailableOutputDevices list
6138 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6139 if (!outProfile->canOpenNewIo()) {
6140 ALOGE("Invalid Output profile max open count %u for profile %s",
6141 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6142 continue;
6143 }
6144 if (!outProfile->hasSupportedDevices()) {
6145 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6146 continue;
6147 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006148 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6149 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006150 mTtsOutputAvailable = true;
6151 }
6152
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006153 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
6154 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
6155 sp<DeviceDescriptor> supportedDevice = 0;
6156 if (supportedDevices.contains(mDefaultOutputDevice)) {
6157 supportedDevice = mDefaultOutputDevice;
6158 } else {
6159 // choose first device present in profile's SupportedDevices also part of
6160 // mAvailableOutputDevices.
6161 if (availProfileDevices.isEmpty()) {
6162 continue;
6163 }
6164 supportedDevice = availProfileDevices.itemAt(0);
6165 }
6166 if (!mOutputDevicesAll.contains(supportedDevice)) {
6167 continue;
6168 }
6169 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6170 mpClientInterface);
6171 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006172 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6173 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006174 AUDIO_STREAM_DEFAULT,
6175 AUDIO_OUTPUT_FLAG_NONE, &output);
6176 if (status != NO_ERROR) {
6177 ALOGW("Cannot open output stream for devices %s on hw module %s",
6178 supportedDevice->toString().c_str(), hwModule->getName());
6179 continue;
6180 }
6181 for (const auto &device : availProfileDevices) {
6182 // give a valid ID to an attached device once confirmed it is reachable
6183 if (!device->isAttached()) {
6184 device->attach(hwModule);
6185 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006186 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006187 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006188 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6189 }
6190 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006191 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006192 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6193 mPrimaryOutput = outputDesc;
6194 }
Eric Laurent39095982021-08-24 18:29:27 +02006195 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006196 outputDesc->close();
6197 } else {
6198 addOutput(output, outputDesc);
6199 setOutputDevices(outputDesc,
6200 DeviceVector(supportedDevice),
6201 true,
6202 0,
6203 NULL);
6204 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006205 }
6206 // open input streams needed to access attached devices to validate
6207 // mAvailableInputDevices list
6208 for (const auto& inProfile : hwModule->getInputProfiles()) {
6209 if (!inProfile->canOpenNewIo()) {
6210 ALOGE("Invalid Input profile max open count %u for profile %s",
6211 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6212 continue;
6213 }
6214 if (!inProfile->hasSupportedDevices()) {
6215 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6216 continue;
6217 }
6218 // chose first device present in profile's SupportedDevices also part of
6219 // available input devices
6220 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
6221 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
6222 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006223 ALOGV("%s: Input device list is empty! for profile %s",
6224 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006225 continue;
6226 }
6227 sp<AudioInputDescriptor> inputDesc =
6228 new AudioInputDescriptor(inProfile, mpClientInterface);
6229
6230 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6231 status_t status = inputDesc->open(nullptr,
6232 availProfileDevices.itemAt(0),
6233 AUDIO_SOURCE_MIC,
6234 AUDIO_INPUT_FLAG_NONE,
6235 &input);
6236 if (status != NO_ERROR) {
6237 ALOGW("Cannot open input stream for device %s on hw module %s",
6238 availProfileDevices.toString().c_str(),
6239 hwModule->getName());
6240 continue;
6241 }
6242 for (const auto &device : availProfileDevices) {
6243 // give a valid ID to an attached device once confirmed it is reachable
6244 if (!device->isAttached()) {
6245 device->attach(hwModule);
6246 device->importAudioPortAndPickAudioProfile(inProfile, true);
6247 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006248 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006249 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6250 }
6251 }
6252 inputDesc->close();
6253 }
6254 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006255
6256 // Check if spatializer outputs can be closed until used.
6257 // mOutputs vector never contains duplicated outputs at this point.
6258 std::vector<audio_io_handle_t> outputsClosed;
6259 for (size_t i = 0; i < mOutputs.size(); i++) {
6260 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6261 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6262 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6263 outputsClosed.push_back(desc->mIoHandle);
6264 desc->close();
6265 }
6266 }
6267 for (auto output : outputsClosed) {
6268 removeOutput(output);
6269 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006270}
6271
Eric Laurent98e38192018-02-15 18:31:53 -08006272void AudioPolicyManager::addOutput(audio_io_handle_t output,
6273 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006274{
Eric Laurent1c333e22014-05-20 10:48:17 -07006275 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006276 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006277 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006278 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006279 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006280}
6281
François Gaffie53615e22015-03-19 09:24:12 +01006282void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6283{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006284 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6285 ALOGV("%s: removing primary output", __func__);
6286 mPrimaryOutput = nullptr;
6287 }
François Gaffie53615e22015-03-19 09:24:12 +01006288 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006289 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006290}
6291
Eric Laurent98e38192018-02-15 18:31:53 -08006292void AudioPolicyManager::addInput(audio_io_handle_t input,
6293 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006294{
Eric Laurent1c333e22014-05-20 10:48:17 -07006295 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006296 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006297}
Eric Laurente552edb2014-03-10 17:42:56 -07006298
François Gaffie11d30102018-11-02 16:09:09 +01006299status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006300 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006301 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006302{
François Gaffie11d30102018-11-02 16:09:09 +01006303 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006304 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006305 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006306
François Gaffie11d30102018-11-02 16:09:09 +01006307 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006308 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006309 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006310 }
Eric Laurente552edb2014-03-10 17:42:56 -07006311
Eric Laurent3b73df72014-03-11 09:06:29 -07006312 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006313 // first call getAudioPort to get the supported attributes from the HAL
6314 struct audio_port_v7 port = {};
6315 device->toAudioPort(&port);
6316 status_t status = mpClientInterface->getAudioPort(&port);
6317 if (status == NO_ERROR) {
6318 device->importAudioPort(port);
6319 }
6320
6321 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006322 for (size_t i = 0; i < mOutputs.size(); i++) {
6323 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006324 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006325 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006326 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6327 mOutputs.keyAt(i), device->toString().c_str());
6328 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006329 }
6330 }
6331 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006332 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006333 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006334 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6335 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006336 if (profile->supportsDevice(device)) {
6337 profiles.add(profile);
6338 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6339 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006340 }
6341 }
6342 }
6343
Eric Laurent7b279bb2015-12-14 10:18:23 -08006344 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006345
Eric Laurente552edb2014-03-10 17:42:56 -07006346 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006347 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006348 return BAD_VALUE;
6349 }
6350
6351 // open outputs for matching profiles if needed. Direct outputs are also opened to
6352 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6353 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006354 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006355
6356 // nothing to do if one output is already opened for this profile
6357 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006358 for (j = 0; j < outputs.size(); j++) {
6359 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006360 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006361 // matching profile: save the sample rates, format and channel masks supported
6362 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006363 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006364 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006365 }
Eric Laurente552edb2014-03-10 17:42:56 -07006366 break;
6367 }
6368 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006369 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006370 continue;
6371 }
6372
Eric Laurent3974e3b2017-12-07 17:58:43 -08006373 if (!profile->canOpenNewIo()) {
6374 ALOGW("Max Output number %u already opened for this profile %s",
6375 profile->maxOpenCount, profile->getTagName().c_str());
6376 continue;
6377 }
6378
Eric Laurent83efe1c2017-07-09 16:51:08 -07006379 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07006380 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006381 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6382 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006383 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006384 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006385 profiles.removeAt(profile_index);
6386 profile_index--;
6387 } else {
6388 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006389 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006390 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006391 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6392 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006393 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006394 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006395
François Gaffie11d30102018-11-02 16:09:09 +01006396 if (device_distinguishes_on_address(deviceType)) {
6397 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6398 device->toString().c_str());
6399 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
6400 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006401 }
Eric Laurente552edb2014-03-10 17:42:56 -07006402 ALOGV("checkOutputsForDevice(): adding output %d", output);
6403 }
6404 }
6405
6406 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006407 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006408 return BAD_VALUE;
6409 }
Eric Laurentd4692962014-05-05 18:13:44 -07006410 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006411 // check if one opened output is not needed any more after disconnecting one device
6412 for (size_t i = 0; i < mOutputs.size(); i++) {
6413 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006414 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006415 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006416 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006417 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006418 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006419 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006420 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6421 mOutputs.keyAt(i));
6422 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006423 }
Eric Laurente552edb2014-03-10 17:42:56 -07006424 }
6425 }
Eric Laurentd4692962014-05-05 18:13:44 -07006426 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006427 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006428 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6429 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006430 if (!profile->supportsDevice(device)) {
6431 continue;
6432 }
6433 ALOGV("checkOutputsForDevice(): "
6434 "clearing direct output profile %zu on module %s",
6435 j, hwModule->getName());
6436 profile->clearAudioProfiles();
6437 if (!profile->hasDynamicAudioProfile()) {
6438 continue;
6439 }
6440 // When a device is disconnected, if there is an IOProfile that contains dynamic
6441 // profiles and supports the disconnected device, call getAudioPort to repopulate
6442 // the capabilities of the devices that is supported by the IOProfile.
6443 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6444 if (supportedDevice == device ||
6445 !mAvailableOutputDevices.contains(supportedDevice)) {
6446 continue;
6447 }
6448 struct audio_port_v7 port;
6449 supportedDevice->toAudioPort(&port);
6450 status_t status = mpClientInterface->getAudioPort(&port);
6451 if (status == NO_ERROR) {
6452 supportedDevice->importAudioPort(port);
6453 }
Eric Laurente552edb2014-03-10 17:42:56 -07006454 }
6455 }
6456 }
6457 }
6458 return NO_ERROR;
6459}
6460
François Gaffie11d30102018-11-02 16:09:09 +01006461status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006462 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006463{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006464 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006465
François Gaffie11d30102018-11-02 16:09:09 +01006466 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006467 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006468 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006469 }
6470
Eric Laurentd4692962014-05-05 18:13:44 -07006471 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006472 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006473 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006474 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006475 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006476 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006477 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006478 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006479
François Gaffie11d30102018-11-02 16:09:09 +01006480 if (profile->supportsDevice(device)) {
6481 profiles.add(profile);
6482 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6483 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006484 }
6485 }
6486 }
6487
Eric Laurent0dd51852019-04-19 18:18:58 -07006488 if (profiles.isEmpty()) {
6489 ALOGW("%s: No input profile available for device %s",
6490 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006491 return BAD_VALUE;
6492 }
6493
6494 // open inputs for matching profiles if needed. Direct inputs are also opened to
6495 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6496 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6497
Eric Laurent1c333e22014-05-20 10:48:17 -07006498 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006499
Eric Laurentd4692962014-05-05 18:13:44 -07006500 // nothing to do if one input is already opened for this profile
6501 size_t input_index;
6502 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6503 desc = mInputs.valueAt(input_index);
6504 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006505 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006506 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006507 }
Eric Laurentd4692962014-05-05 18:13:44 -07006508 break;
6509 }
6510 }
6511 if (input_index != mInputs.size()) {
6512 continue;
6513 }
6514
Eric Laurent3974e3b2017-12-07 17:58:43 -08006515 if (!profile->canOpenNewIo()) {
6516 ALOGW("Max Input number %u already opened for this profile %s",
6517 profile->maxOpenCount, profile->getTagName().c_str());
6518 continue;
6519 }
6520
Eric Laurentfe231122017-11-17 17:48:06 -08006521 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006522 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006523 status_t status = desc->open(nullptr,
6524 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006525 AUDIO_SOURCE_MIC,
6526 AUDIO_INPUT_FLAG_NONE,
6527 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006528
Eric Laurentcf2c0212014-07-25 16:20:43 -07006529 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006530 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006531 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006532 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006533 mpClientInterface->setParameters(input, String8(param));
6534 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006535 }
François Gaffie11d30102018-11-02 16:09:09 +01006536 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006537 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006538 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006539 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006540 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006541 }
6542
Eric Laurent0dd51852019-04-19 18:18:58 -07006543 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006544 addInput(input, desc);
6545 }
6546 } // endif input != 0
6547
Eric Laurentcf2c0212014-07-25 16:20:43 -07006548 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006549 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006550 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006551 profiles.removeAt(profile_index);
6552 profile_index--;
6553 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006554 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006555 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006556 }
Eric Laurentd4692962014-05-05 18:13:44 -07006557 ALOGV("checkInputsForDevice(): adding input %d", input);
6558 }
6559 } // end scan profiles
6560
6561 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006562 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006563 return BAD_VALUE;
6564 }
6565 } else {
6566 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006567 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006568 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006569 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006570 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006571 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006572 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006573 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006574 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6575 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006576 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006577 }
6578 }
6579 }
6580 } // end disconnect
6581
6582 return NO_ERROR;
6583}
6584
6585
Eric Laurente0720872014-03-11 09:30:41 -07006586void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006587{
6588 ALOGV("closeOutput(%d)", output);
6589
François Gaffie1c878552018-11-22 16:53:21 +01006590 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6591 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006592 ALOGW("closeOutput() unknown output %d", output);
6593 return;
6594 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006595 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006596 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006597
Eric Laurente552edb2014-03-10 17:42:56 -07006598 // look for duplicated outputs connected to the output being removed.
6599 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006600 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6601 if (dupOutput->isDuplicated() &&
6602 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6603 sp<SwAudioOutputDescriptor> remainingOutput =
6604 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006605 // As all active tracks on duplicated output will be deleted,
6606 // and as they were also referenced on the other output, the reference
6607 // count for their stream type must be adjusted accordingly on
6608 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006609 const bool wasActive = remainingOutput->isActive();
6610 // Note: no-op on the closing output where all clients has already been set inactive
6611 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006612 // stop() will be a no op if the output is still active but is needed in case all
6613 // active streams refcounts where cleared above
6614 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006615 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006616 }
Eric Laurente552edb2014-03-10 17:42:56 -07006617 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6618 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6619
6620 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006621 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006622 }
6623 }
6624
Eric Laurent05b90f82014-08-27 15:32:29 -07006625 nextAudioPortGeneration();
6626
François Gaffie1c878552018-11-22 16:53:21 +01006627 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006628 if (index >= 0) {
6629 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006630 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6631 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006632 mAudioPatches.removeItemsAt(index);
6633 mpClientInterface->onAudioPatchListUpdate();
6634 }
6635
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006636 if (closingOutputWasActive) {
6637 closingOutput->stop();
6638 }
François Gaffie1c878552018-11-22 16:53:21 +01006639 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006640
François Gaffie53615e22015-03-19 09:24:12 +01006641 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006642 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006643 if (closingOutput == mSpatializerOutput) {
6644 mSpatializerOutput.clear();
6645 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006646
6647 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6648 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006649 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006650 bool directOutputOpen = false;
6651 for (size_t i = 0; i < mOutputs.size(); i++) {
6652 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6653 directOutputOpen = true;
6654 break;
6655 }
6656 }
6657 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006658 ALOGV("no direct outputs open, reset MSD patches");
6659 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6660 // how output devices for patching are resolved. Avoid by caching and reusing the
6661 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6662 // devices to patch to. This may be complicated by the fact that devices may become
6663 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006664 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006665 }
6666 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006667}
6668
6669void AudioPolicyManager::closeInput(audio_io_handle_t input)
6670{
6671 ALOGV("closeInput(%d)", input);
6672
6673 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6674 if (inputDesc == NULL) {
6675 ALOGW("closeInput() unknown input %d", input);
6676 return;
6677 }
6678
Eric Laurent6a94d692014-05-20 11:18:06 -07006679 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006680
François Gaffie11d30102018-11-02 16:09:09 +01006681 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006682 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006683 if (index >= 0) {
6684 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006685 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6686 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006687 mAudioPatches.removeItemsAt(index);
6688 mpClientInterface->onAudioPatchListUpdate();
6689 }
6690
Eric Laurentfe231122017-11-17 17:48:06 -08006691 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006692 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006693
François Gaffie11d30102018-11-02 16:09:09 +01006694 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6695 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006696 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006697 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006698 }
Eric Laurente552edb2014-03-10 17:42:56 -07006699}
6700
François Gaffie11d30102018-11-02 16:09:09 +01006701SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6702 const DeviceVector &devices,
6703 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006704{
6705 SortedVector<audio_io_handle_t> outputs;
6706
François Gaffie11d30102018-11-02 16:09:09 +01006707 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006708 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006709 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006710 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006711 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006712 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006713 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006714 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006715 outputs.add(openOutputs.keyAt(i));
6716 }
6717 }
6718 return outputs;
6719}
6720
Mikhail Naganov37977152018-07-11 15:54:44 -07006721void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6722{
6723 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6724 // output is suspended before any tracks are moved to it
6725 checkA2dpSuspend();
6726 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006727 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006728 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006729 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006730 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006731 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6732 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6733 // configuration changes will ultimately be rerouted correctly. We can still avoid
6734 // unnecessary rerouting by caching and reusing the arguments to
6735 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6736 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006737 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006738 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006739 // an event that changed routing likely occurred, inform upper layers
6740 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006741}
6742
François Gaffiec005e562018-11-06 15:04:49 +01006743bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6744 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006745{
François Gaffiec005e562018-11-06 15:04:49 +01006746 return mEngine->getProductStrategyForAttributes(lAttr) ==
6747 mEngine->getProductStrategyForAttributes(rAttr);
6748}
6749
Francois Gaffieff1eb522020-05-06 18:37:04 +02006750void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6751{
6752 for (size_t i = 0; i < mAudioSources.size(); i++) {
6753 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6754 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006755 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006756 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006757 connectAudioSource(sourceDesc);
6758 }
6759 }
6760}
6761
6762void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6763{
6764 for (size_t i = 0; i < mAudioSources.size(); i++) {
6765 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6766 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6767 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6768 disconnectAudioSource(sourceDesc);
6769 }
6770 }
6771}
6772
François Gaffiec005e562018-11-06 15:04:49 +01006773void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6774{
6775 auto psId = mEngine->getProductStrategyForAttributes(attr);
6776
6777 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6778 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006779
François Gaffie11d30102018-11-02 16:09:09 +01006780 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6781 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006782
Eric Laurentc209fe42020-06-05 18:11:23 -07006783 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006784 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006785 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006786 // take into account dynamic audio policies related changes: if a client is now associated
6787 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006788 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006789 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6790 if (desc->isDuplicated()) {
6791 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006792 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006793 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6794 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6795 continue;
6796 }
6797 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006798 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006799 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6800 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6801 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006802 if (status != OK) {
6803 continue;
6804 }
yucliuf4de36d2020-09-14 14:57:56 -07006805 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006806 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006807 maxLatency = desc->latency();
6808 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006809 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006810 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006811 }
6812 }
6813
Eric Laurent56ed8842022-11-15 16:04:41 +01006814 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006815 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6816 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006817 for (audio_io_handle_t srcOut : srcOutputs) {
6818 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006819 if (desc == nullptr) continue;
6820
6821 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006822 maxLatency = desc->latency();
6823 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006824
Eric Laurent56ed8842022-11-15 16:04:41 +01006825 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006826 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006827 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006828 // a client on a non direct outputs has necessarily a linear PCM format
6829 // so we can call selectOutput() safely
6830 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6831 client->flags(),
6832 client->config().format,
6833 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006834 client->config().sample_rate,
6835 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006836 if (newOutput != srcOut) {
6837 invalidate = true;
6838 break;
6839 }
6840 } else {
6841 sp<IOProfile> profile = getProfileForOutput(newDevices,
6842 client->config().sample_rate,
6843 client->config().format,
6844 client->config().channel_mask,
6845 client->flags(),
6846 true /* directOnly */);
6847 if (profile != desc->mProfile) {
6848 invalidate = true;
6849 break;
6850 }
6851 }
6852 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006853 // mute strategy while moving tracks from one output to another
6854 if (invalidate) {
6855 invalidatedOutputs.push_back(desc);
6856 if (desc->isStrategyActive(psId)) {
6857 setStrategyMute(psId, true, desc);
6858 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6859 newDevices.types());
6860 }
Eric Laurente552edb2014-03-10 17:42:56 -07006861 }
François Gaffiec005e562018-11-06 15:04:49 +01006862 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006863 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006864 connectAudioSource(source);
6865 }
Eric Laurente552edb2014-03-10 17:42:56 -07006866 }
6867
Eric Laurent56ed8842022-11-15 16:04:41 +01006868 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6869 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6870 std::to_string(srcOutputs[0]).c_str(),
6871 std::to_string(dstOutputs[0]).c_str());
6872
François Gaffiec005e562018-11-06 15:04:49 +01006873 // Move effects associated to this stream from previous output to new output
6874 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006875 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006876 }
François Gaffiec005e562018-11-06 15:04:49 +01006877 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006878 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006879 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006880 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006881 desc->setTracksInvalidatedStatusByStrategy(psId);
6882 }
Eric Laurente552edb2014-03-10 17:42:56 -07006883 }
6884 }
6885}
6886
Eric Laurente0720872014-03-11 09:30:41 -07006887void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006888{
François Gaffiec005e562018-11-06 15:04:49 +01006889 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6890 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6891 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006892 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006893 }
Eric Laurente552edb2014-03-10 17:42:56 -07006894}
6895
Kevin Rocard153f92d2018-12-18 18:33:28 -08006896void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08006897 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006898 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006899 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006900 for (size_t i = 0; i < mOutputs.size(); i++) {
6901 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6902 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006903 sp<AudioPolicyMix> primaryMix;
6904 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006905 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006906 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6907 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
6908 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006909 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6910 for (auto &secondaryMix : secondaryMixes) {
6911 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6912 if (outputDesc != nullptr &&
6913 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6914 secondaryDescs.push_back(outputDesc);
6915 }
6916 }
6917
jiabinc44b3462022-12-08 12:52:31 -08006918 if (status != OK &&
6919 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
6920 // When it failed to query secondary output, only invalidate the client that is not
6921 // MMAP. The reason is that MMAP stream will not support secondary output.
6922 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00006923 } else if (!std::equal(
6924 client->getSecondaryOutputs().begin(),
6925 client->getSecondaryOutputs().end(),
6926 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006927 if (!audio_is_linear_pcm(client->config().format)) {
6928 // If the format is not PCM, the tracks should be invalidated to get correct
6929 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08006930 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00006931 } else {
6932 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6933 std::vector<audio_io_handle_t> secondaryOutputIds;
6934 for (const auto &secondaryDesc: secondaryDescs) {
6935 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6936 weakSecondaryDescs.push_back(secondaryDesc);
6937 }
6938 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6939 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006940 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006941 }
6942 }
6943 }
jiabin10a03f12021-05-07 23:46:28 +00006944 if (!trackSecondaryOutputs.empty()) {
6945 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6946 }
jiabinc44b3462022-12-08 12:52:31 -08006947 if (!clientsToInvalidate.empty()) {
6948 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
6949 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006950 }
6951}
6952
Eric Laurent2517af32020-11-25 15:31:27 +01006953bool AudioPolicyManager::isScoRequestedForComm() const {
6954 AudioDeviceTypeAddrVector devices;
6955 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6956 for (const auto &device : devices) {
6957 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6958 return true;
6959 }
6960 }
6961 return false;
6962}
6963
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006964bool AudioPolicyManager::isHearingAidUsedForComm() const {
6965 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6966 true /*fromCache*/);
6967 for (const auto &device : devices) {
6968 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6969 return true;
6970 }
6971 }
6972 return false;
6973}
6974
6975
Eric Laurente0720872014-03-11 09:30:41 -07006976void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006977{
François Gaffie53615e22015-03-19 09:24:12 +01006978 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006979 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006980 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006981 return;
6982 }
6983
Eric Laurent3a4311c2014-03-17 12:00:47 -07006984 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006985 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6986 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006987 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006988
6989 // if suspended, restore A2DP output if:
6990 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006991 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006992 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006993 //
Eric Laurentf732e072016-08-03 19:30:28 -07006994 // if not suspended, suspend A2DP output if:
6995 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006996 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006997 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006998 //
6999 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007000 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007001 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007002 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007003 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007004
7005 mpClientInterface->restoreOutput(a2dpOutput);
7006 mA2dpSuspended = false;
7007 }
7008 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007009 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007010 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007011 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007012 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007013
7014 mpClientInterface->suspendOutput(a2dpOutput);
7015 mA2dpSuspended = true;
7016 }
7017 }
7018}
7019
François Gaffie11d30102018-11-02 16:09:09 +01007020DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7021 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007022{
François Gaffie11d30102018-11-02 16:09:09 +01007023 DeviceVector devices;
7024
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007025 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007026 if (index >= 0) {
7027 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007028 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007029 ALOGV("%s device %s forced by patch %d", __func__,
7030 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7031 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007032 }
7033 }
7034
Dean Wheatley514b4312020-06-17 21:45:00 +10007035 // Do not retrieve engine device for outputs through MSD
7036 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7037 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7038 return outputDesc->devices();
7039 }
7040
Eric Laurent97ac8712018-07-27 18:59:02 -07007041 // Honor explicit routing requests only if no client using default routing is active on this
7042 // input: a specific app can not force routing for other apps by setting a preferred device.
7043 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007044 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007045 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007046 if (device != nullptr) {
7047 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007048 }
7049
François Gaffiea807ef92018-11-05 10:44:33 +01007050 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7051 // of setForceUse / Default Bus device here
7052 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7053 if (device != nullptr) {
7054 return DeviceVector(device);
7055 }
7056
François Gaffiec005e562018-11-06 15:04:49 +01007057 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7058 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7059 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307060 auto hasStreamActive = [&](auto stream) {
7061 return hasStream(streams, stream) && isStreamActive(stream, 0);
7062 };
Eric Laurent484e9272018-06-07 17:29:23 -07007063
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307064 auto doGetOutputDevicesForVoice = [&]() {
7065 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007066 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307067 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007068 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7069 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307070 };
7071
7072 // With low-latency playing on speaker, music on WFD, when the first low-latency
7073 // output is stopped, getNewOutputDevices checks for a product strategy
7074 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007075 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307076 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7077 // stream is associated to the output descriptor.
7078 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7079 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7080 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7081 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007082 // Retrieval of devices for voice DL is done on primary output profile, cannot
7083 // check the route (would force modifying configuration file for this profile)
7084 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7085 break;
7086 }
Eric Laurente552edb2014-03-10 17:42:56 -07007087 }
François Gaffiec005e562018-11-06 15:04:49 +01007088 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007089 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007090}
7091
François Gaffie11d30102018-11-02 16:09:09 +01007092sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7093 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007094{
François Gaffie11d30102018-11-02 16:09:09 +01007095 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007096
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007097 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007098 if (index >= 0) {
7099 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007100 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007101 ALOGV("getNewInputDevice() device %s forced by patch %d",
7102 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7103 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007104 }
7105 }
7106
Eric Laurent97ac8712018-07-27 18:59:02 -07007107 // Honor explicit routing requests only if no client using default routing is active on this
7108 // input: a specific app can not force routing for other apps by setting a preferred device.
7109 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007110 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7111 if (device != nullptr) {
7112 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007113 }
7114
Eric Laurentdc95a252018-04-12 12:46:56 -07007115 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007116 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007117 audio_attributes_t attributes;
7118 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007119 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007120 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7121 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007122 attributes = topClient->attributes();
7123 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007124 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007125 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007126 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7127 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007128 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007129 }
7130
Francois Gaffie716e1432019-01-14 16:58:59 +01007131 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7132 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007133 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007134 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007135 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007136 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007137
Eric Laurente552edb2014-03-10 17:42:56 -07007138 return device;
7139}
7140
Eric Laurent794fde22016-03-11 09:50:45 -08007141bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7142 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007143 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007144}
7145
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007146status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007147 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007148 if (devices == nullptr) {
7149 return BAD_VALUE;
7150 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007151
Andy Hung6d23c0f2022-02-16 09:37:15 -08007152 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007153 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7154 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007155 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007156 for (const auto& device : curDevices) {
7157 devices->push_back(device->getDeviceTypeAddr());
7158 }
7159 return NO_ERROR;
7160}
7161
Eric Laurente0720872014-03-11 09:30:41 -07007162void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007163 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007164 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007165 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007166 updateDevicesAndOutputs();
7167 break;
7168 default:
7169 break;
7170 }
7171}
7172
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007173uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007174
7175 // skip beacon mute management if a dedicated TTS output is available
7176 if (mTtsOutputAvailable) {
7177 return 0;
7178 }
7179
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007180 switch(event) {
7181 case STARTING_OUTPUT:
7182 mBeaconMuteRefCount++;
7183 break;
7184 case STOPPING_OUTPUT:
7185 if (mBeaconMuteRefCount > 0) {
7186 mBeaconMuteRefCount--;
7187 }
7188 break;
7189 case STARTING_BEACON:
7190 mBeaconPlayingRefCount++;
7191 break;
7192 case STOPPING_BEACON:
7193 if (mBeaconPlayingRefCount > 0) {
7194 mBeaconPlayingRefCount--;
7195 }
7196 break;
7197 }
7198
7199 if (mBeaconMuteRefCount > 0) {
7200 // any playback causes beacon to be muted
7201 return setBeaconMute(true);
7202 } else {
7203 // no other playback: unmute when beacon starts playing, mute when it stops
7204 return setBeaconMute(mBeaconPlayingRefCount == 0);
7205 }
7206}
7207
7208uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7209 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7210 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7211 // keep track of muted state to avoid repeating mute/unmute operations
7212 if (mBeaconMuted != mute) {
7213 // mute/unmute AUDIO_STREAM_TTS on all outputs
7214 ALOGV("\t muting %d", mute);
7215 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007216 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7217 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7218 ALOGV("\t no tts volume source available");
7219 return 0;
7220 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007221 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007222 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007223 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007224 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007225 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007226 maxLatency = latency;
7227 }
7228 }
7229 mBeaconMuted = mute;
7230 return maxLatency;
7231 }
7232 return 0;
7233}
7234
Eric Laurente0720872014-03-11 09:30:41 -07007235void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007236{
François Gaffiec005e562018-11-06 15:04:49 +01007237 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007238 mPreviousOutputs = mOutputs;
7239}
7240
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007241uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007242 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007243 uint32_t delayMs)
7244{
7245 // mute/unmute strategies using an incompatible device combination
7246 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7247 // if unmuting, unmute only after the specified delay
7248 if (outputDesc->isDuplicated()) {
7249 return 0;
7250 }
7251
7252 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007253 DeviceVector devices = outputDesc->devices();
7254 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007255
François Gaffiec005e562018-11-06 15:04:49 +01007256 auto productStrategies = mEngine->getOrderedProductStrategies();
7257 for (const auto &productStrategy : productStrategies) {
7258 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7259 DeviceVector curDevices =
7260 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7261 curDevices = curDevices.filter(outputDesc->supportedDevices());
7262 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007263 bool doMute = false;
7264
François Gaffiec005e562018-11-06 15:04:49 +01007265 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007266 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007267 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7268 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007269 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007270 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007271 }
Eric Laurent99401132014-05-07 19:48:15 -07007272 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007273 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007274 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007275 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007276 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007277 continue;
7278 }
François Gaffiec005e562018-11-06 15:04:49 +01007279 ALOGVV("%s() %s (curDevice %s)", __func__,
7280 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7281 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7282 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007283 if (mute) {
7284 // FIXME: should not need to double latency if volume could be applied
7285 // immediately by the audioflinger mixer. We must account for the delay
7286 // between now and the next time the audioflinger thread for this output
7287 // will process a buffer (which corresponds to one buffer size,
7288 // usually 1/2 or 1/4 of the latency).
7289 if (muteWaitMs < desc->latency() * 2) {
7290 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007291 }
7292 }
7293 }
7294 }
7295 }
7296 }
7297
Eric Laurent99401132014-05-07 19:48:15 -07007298 // temporary mute output if device selection changes to avoid volume bursts due to
7299 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007300 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007301 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007302
Eric Laurentdc462862016-07-19 12:29:53 -07007303 if (muteWaitMs < tempMuteWaitMs) {
7304 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007305 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007306
7307 // If recommended duration is defined, replace temporary mute duration to avoid
7308 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7309 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7310 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7311 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7312 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7313
François Gaffieaaac0fd2018-11-22 17:56:39 +01007314 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7315 // make sure that we do not start the temporary mute period too early in case of
7316 // delayed device change
7317 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7318 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007319 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007320 }
7321 }
7322
Eric Laurente552edb2014-03-10 17:42:56 -07007323 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7324 if (muteWaitMs > delayMs) {
7325 muteWaitMs -= delayMs;
7326 usleep(muteWaitMs * 1000);
7327 return muteWaitMs;
7328 }
7329 return 0;
7330}
7331
François Gaffie11d30102018-11-02 16:09:09 +01007332uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7333 const DeviceVector &devices,
7334 bool force,
7335 int delayMs,
7336 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02007337 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07007338{
jiabin3ff8d7d2022-12-13 06:27:44 +00007339 // TODO(b/262404095): Consider if the output need to be reopened.
François Gaffie11d30102018-11-02 16:09:09 +01007340 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007341 uint32_t muteWaitMs;
7342
7343 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01007344 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
7345 nullptr /* patchHandle */, requiresMuteCheck);
7346 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
7347 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07007348 return muteWaitMs;
7349 }
Eric Laurente552edb2014-03-10 17:42:56 -07007350
7351 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007352 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007353 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007354 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007355
François Gaffie11d30102018-11-02 16:09:09 +01007356 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7357
7358 if (!filteredDevices.isEmpty()) {
7359 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007360 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007361
7362 // if the outputs are not materially active, there is no need to mute.
7363 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007364 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007365 } else {
7366 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7367 muteWaitMs = 0;
7368 }
Eric Laurente552edb2014-03-10 17:42:56 -07007369
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007370 bool outputRouted = outputDesc->isRouted();
7371
Eric Laurent79ea9582020-06-11 18:49:24 -07007372 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7373 // output profile or if new device is not supported AND previous device(s) is(are) still
7374 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007375 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007376 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7377 // restore previous device after evaluating strategy mute state
7378 outputDesc->setDevices(prevDevices);
7379 return muteWaitMs;
7380 }
7381
Eric Laurente552edb2014-03-10 17:42:56 -07007382 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007383 // the requested device is AUDIO_DEVICE_NONE
7384 // OR the requested device is the same as current device
7385 // AND force is not specified
7386 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007387 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007388 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007389 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7390 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007391 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7392 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7393 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7394 }
Eric Laurente552edb2014-03-10 17:42:56 -07007395 return muteWaitMs;
7396 }
7397
François Gaffie11d30102018-11-02 16:09:09 +01007398 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007399
Eric Laurente552edb2014-03-10 17:42:56 -07007400 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007401 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007402 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007403 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007404 PatchBuilder patchBuilder;
7405 patchBuilder.addSource(outputDesc);
7406 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7407 for (const auto &filteredDevice : filteredDevices) {
7408 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007409 }
7410
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007411 // Add half reported latency to delayMs when muteWaitMs is null in order
7412 // to avoid disordered sequence of muting volume and changing devices.
7413 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7414 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007415 }
Eric Laurente552edb2014-03-10 17:42:56 -07007416
7417 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007418 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007419
7420 return muteWaitMs;
7421}
7422
Eric Laurentc75307b2015-03-17 15:29:32 -07007423status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007424 int delayMs,
7425 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007426{
Eric Laurent6a94d692014-05-20 11:18:06 -07007427 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007428 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7429 return INVALID_OPERATION;
7430 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007431 if (patchHandle) {
7432 index = mAudioPatches.indexOfKey(*patchHandle);
7433 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007434 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007435 }
7436 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007437 return INVALID_OPERATION;
7438 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007439 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007440 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007441 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007442 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007443 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007444 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007445 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007446 return status;
7447}
7448
7449status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007450 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007451 bool force,
7452 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007453{
7454 status_t status = NO_ERROR;
7455
Eric Laurent1f2f2232014-06-02 12:01:23 -07007456 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007457 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7458 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007459
François Gaffie11d30102018-11-02 16:09:09 +01007460 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007461 PatchBuilder patchBuilder;
7462 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007463 // AUDIO_SOURCE_HOTWORD is for internal use only:
7464 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007465 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7466 auto result = usecase;
7467 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7468 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7469 }
7470 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007471 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007472 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007473 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007474 }
7475 }
7476 return status;
7477}
7478
Eric Laurent6a94d692014-05-20 11:18:06 -07007479status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7480 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007481{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007482 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007483 ssize_t index;
7484 if (patchHandle) {
7485 index = mAudioPatches.indexOfKey(*patchHandle);
7486 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007487 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007488 }
7489 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007490 return INVALID_OPERATION;
7491 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007492 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007493 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007494 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007495 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007496 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007497 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007498 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007499 return status;
7500}
7501
François Gaffie11d30102018-11-02 16:09:09 +01007502sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007503 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007504 audio_format_t& format,
7505 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007506 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007507{
7508 // Choose an input profile based on the requested capture parameters: select the first available
7509 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007510 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007511 //
7512 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7513 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007514
Atneya Nair0f0a8032022-12-12 16:20:12 -08007515 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7516 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7517 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7518
7519 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007520
jiabin2fd710d2022-05-02 23:20:22 +00007521 for (;;) {
7522 sp<IOProfile> firstInexact = nullptr;
7523 uint32_t updatedSamplingRate = 0;
7524 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7525 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7526 for (const auto& hwModule : mHwModules) {
7527 for (const auto& profile : hwModule->getInputProfiles()) {
7528 // profile->log();
7529 //updatedFormat = format;
7530 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7531 &samplingRate /*updatedSamplingRate*/,
7532 format,
7533 &format, /*updatedFormat*/
7534 channelMask,
7535 &channelMask /*updatedChannelMask*/,
7536 // FIXME ugly cast
7537 (audio_output_flags_t) flags,
7538 true /*exactMatchRequiredForInputFlags*/)) {
7539 return profile;
7540 }
7541 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7542 samplingRate,
7543 &updatedSamplingRate,
7544 format,
7545 &updatedFormat,
7546 channelMask,
7547 &updatedChannelMask,
7548 // FIXME ugly cast
7549 (audio_output_flags_t) flags,
7550 false /*exactMatchRequiredForInputFlags*/)) {
7551 firstInexact = profile;
7552 }
7553 }
7554 }
7555
7556 if (firstInexact != nullptr) {
7557 samplingRate = updatedSamplingRate;
7558 format = updatedFormat;
7559 channelMask = updatedChannelMask;
7560 return firstInexact;
7561 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7562 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7563 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7564 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7565 flags = AUDIO_INPUT_FLAG_NONE;
7566 } else { // fail
7567 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7568 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7569 samplingRate, format, channelMask, oriFlags);
7570 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007571 }
7572 }
jiabin2fd710d2022-05-02 23:20:22 +00007573
7574 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007575}
7576
François Gaffieaaac0fd2018-11-22 17:56:39 +01007577float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7578 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007579 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007580 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007581{
jiabin9a3361e2019-10-01 09:38:30 -07007582 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007583
7584 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7585 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7586 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7587 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007588 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7589 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7590 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7591 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7592 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007593
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007594 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007595 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7596 mOutputs.isActive(ringVolumeSrc, 0)) {
7597 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007598 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007599 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007600 }
7601
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007602 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007603 if ((volumeSource != callVolumeSrc && (isInCall() ||
7604 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007605 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007606 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7607 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007608 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7609 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7610 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007611 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007612 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007613 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007614 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007615 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007616 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007617 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7618 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7619 // programmatically muted.
7620 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7621 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7622 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007623 bool exemptFromCapping =
7624 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7625 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007626 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7627 volumeSource, volumeDb);
7628 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007629 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7630 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7631 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007632 }
7633 }
Eric Laurente552edb2014-03-10 17:42:56 -07007634 // if a headset is connected, apply the following rules to ring tones and notifications
7635 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007636 // - always attenuate notifications volume by 6dB
7637 // - attenuate ring tones volume by 6dB unless music is not playing and
7638 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007639 // - if music is playing, always limit the volume to current music volume,
7640 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007641 if (!Intersection(deviceTypes,
7642 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7643 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007644 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7645 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007646 ((volumeSource == alarmVolumeSrc ||
7647 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007648 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7649 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7650 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007651 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7652 curves.canBeMuted()) {
7653
Eric Laurente552edb2014-03-10 17:42:56 -07007654 // when the phone is ringing we must consider that music could have been paused just before
7655 // by the music application and behave as if music was active if the last music track was
7656 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007657 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007658 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007659 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007660 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007661 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7662 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007663 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007664 float musicVolDb = computeVolume(musicCurves,
7665 musicVolumeSrc,
7666 musicCurves.getVolumeIndex(musicDevice),
7667 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007668 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7669 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7670 if (volumeDb > minVolDb) {
7671 volumeDb = minVolDb;
7672 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007673 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007674 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7675 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7676 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007677 // on A2DP, also ensure notification volume is not too low compared to media when
7678 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007679 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007680 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007681 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7682 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007683 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7684 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007685 }
7686 }
jiabin9a3361e2019-10-01 09:38:30 -07007687 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007688 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007689 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007690 }
7691 }
7692
François Gaffie43c73442018-11-08 08:21:55 +01007693 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007694}
7695
Eric Laurent3839bc02018-07-10 18:33:34 -07007696int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007697 VolumeSource fromVolumeSource,
7698 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007699{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007700 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007701 return srcIndex;
7702 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007703 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7704 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007705 float minSrc = (float)srcCurves.getVolumeIndexMin();
7706 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7707 float minDst = (float)dstCurves.getVolumeIndexMin();
7708 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007709
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007710 // preserve mute request or correct range
7711 if (srcIndex < minSrc) {
7712 if (srcIndex == 0) {
7713 return 0;
7714 }
7715 srcIndex = minSrc;
7716 } else if (srcIndex > maxSrc) {
7717 srcIndex = maxSrc;
7718 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007719 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7720}
7721
François Gaffieaaac0fd2018-11-22 17:56:39 +01007722status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7723 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007724 int index,
7725 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007726 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007727 int delayMs,
7728 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007729{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007730 // do not change actual attributes volume if the attributes is muted
7731 if (outputDesc->isMuted(volumeSource)) {
7732 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7733 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007734 return NO_ERROR;
7735 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007736 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7737 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7738 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7739 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007740
Eric Laurent2517af32020-11-25 15:31:27 +01007741 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007742 bool isHAUsed = isHearingAidUsedForComm();
7743
Eric Laurente552edb2014-03-10 17:42:56 -07007744 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007745 // if sco and call follow same curves, bypass forceUseForComm
7746 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007747 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007748 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7749 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007750 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007751 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007752 // Do not return an error here as AudioService will always set both voice call
7753 // and bluetooth SCO volumes due to stream aliasing.
7754 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007755 }
jiabin9a3361e2019-10-01 09:38:30 -07007756 if (deviceTypes.empty()) {
7757 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007758 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007759
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007760 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7761 ALOGE("invalid volume index range");
7762 return BAD_VALUE;
7763 }
7764
jiabin9a3361e2019-10-01 09:38:30 -07007765 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7766 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007767 // Force VoIP volume to max for bluetooth SCO device except if muted
7768 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007769 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007770 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007771 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007772 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007773 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007774 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007775
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007776 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007777 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007778 // 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 +01007779 if (isVoiceVolSrc) {
7780 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007781 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007782 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007783 }
Eric Laurent18fba842016-03-31 14:41:26 -07007784 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007785 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7786 mLastVoiceVolume = voiceVolume;
7787 }
7788 }
Eric Laurente552edb2014-03-10 17:42:56 -07007789 return NO_ERROR;
7790}
7791
Eric Laurentc75307b2015-03-17 15:29:32 -07007792void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007793 const DeviceTypeSet& deviceTypes,
7794 int delayMs,
7795 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007796{
jiabincd510522020-01-22 09:40:55 -08007797 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007798 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7799 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7800 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007801 curves.getVolumeIndex(deviceTypes),
7802 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007803 }
7804}
7805
François Gaffiec005e562018-11-06 15:04:49 +01007806void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7807 bool on,
7808 const sp<AudioOutputDescriptor>& outputDesc,
7809 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007810 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007811{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007812 std::vector<VolumeSource> sourcesToMute;
7813 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7814 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7815 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007816 VolumeSource source = toVolumeSource(attributes, false);
7817 if ((source != VOLUME_SOURCE_NONE) &&
7818 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7819 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007820 sourcesToMute.push_back(source);
7821 }
Eric Laurente552edb2014-03-10 17:42:56 -07007822 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007823 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007824 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007825 }
7826
Eric Laurente552edb2014-03-10 17:42:56 -07007827}
7828
François Gaffieaaac0fd2018-11-22 17:56:39 +01007829void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7830 bool on,
7831 const sp<AudioOutputDescriptor>& outputDesc,
7832 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007833 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007834{
jiabin9a3361e2019-10-01 09:38:30 -07007835 if (deviceTypes.empty()) {
7836 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007837 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007838 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007839 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007840 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007841 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007842 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007843 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7844 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007845 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007846 }
7847 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007848 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7849 // ignored
7850 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007851 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007852 if (!outputDesc->isMuted(volumeSource)) {
7853 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007854 return;
7855 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007856 if (outputDesc->decMuteCount(volumeSource) == 0) {
7857 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007858 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007859 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007860 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007861 delayMs);
7862 }
7863 }
7864}
7865
François Gaffie53615e22015-03-19 09:24:12 +01007866bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7867{
François Gaffiec005e562018-11-06 15:04:49 +01007868 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007869 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7870 return true;
7871 }
7872
7873 // has known usage?
7874 switch (paa->usage) {
7875 case AUDIO_USAGE_UNKNOWN:
7876 case AUDIO_USAGE_MEDIA:
7877 case AUDIO_USAGE_VOICE_COMMUNICATION:
7878 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7879 case AUDIO_USAGE_ALARM:
7880 case AUDIO_USAGE_NOTIFICATION:
7881 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7882 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7883 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7884 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7885 case AUDIO_USAGE_NOTIFICATION_EVENT:
7886 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7887 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7888 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7889 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007890 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007891 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007892 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007893 case AUDIO_USAGE_EMERGENCY:
7894 case AUDIO_USAGE_SAFETY:
7895 case AUDIO_USAGE_VEHICLE_STATUS:
7896 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007897 break;
7898 default:
7899 return false;
7900 }
7901 return true;
7902}
7903
François Gaffie2110e042015-03-24 08:41:51 +01007904audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7905{
7906 return mEngine->getForceUse(usage);
7907}
7908
Eric Laurent96d1dda2022-03-14 17:14:19 +01007909bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007910 return isStateInCall(mEngine->getPhoneState());
7911}
7912
Eric Laurent96d1dda2022-03-14 17:14:19 +01007913bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007914 return is_state_in_call(state);
7915}
7916
Eric Laurentf9cccec2022-11-16 19:12:00 +01007917bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007918 audio_mode_t mode = mEngine->getPhoneState();
7919 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007920 || (mode == AUDIO_MODE_CALL_SCREEN)
7921 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007922}
7923
Eric Laurentf9cccec2022-11-16 19:12:00 +01007924bool AudioPolicyManager::isInCallOrScreening() const {
7925 audio_mode_t mode = mEngine->getPhoneState();
7926 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7927}
7928
Eric Laurentd60560a2015-04-10 11:31:20 -07007929void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7930{
7931 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007932 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007933 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007934 sourceDesc->sinkDevice()->equals(deviceDesc))
7935 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007936 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007937 }
7938 }
7939
7940 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7941 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7942 bool release = false;
7943 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7944 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7945 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7946 source->ext.device.type == deviceDesc->type()) {
7947 release = true;
7948 }
7949 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007950 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007951 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7952 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7953 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007954 sink->ext.device.type == deviceDesc->type() &&
7955 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7956 || strncmp(sink->ext.device.address, address,
7957 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007958 release = true;
7959 }
7960 }
7961 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007962 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7963 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007964 }
7965 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007966
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007967 mInputs.clearSessionRoutesForDevice(deviceDesc);
7968
Francois Gaffie716e1432019-01-14 16:58:59 +01007969 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007970}
7971
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007972void AudioPolicyManager::modifySurroundFormats(
7973 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007974 std::unordered_set<audio_format_t> enforcedSurround(
7975 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007976 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7977 for (const auto& pair : mConfig.getSurroundFormats()) {
7978 allSurround.insert(pair.first);
7979 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7980 }
Phil Burk09bc4612016-02-24 15:58:15 -08007981
7982 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7983 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007984 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007985 // This is the resulting set of formats depending on the surround mode:
7986 // 'all surround' = allSurround
7987 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7988 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7989 // 'manual surround' = mManualSurroundFormats
7990 // AUTO: formats v 'enforced surround'
7991 // ALWAYS: formats v 'all surround' v 'enforced surround'
7992 // NEVER: formats ^ 'non-surround'
7993 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007994
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007995 std::unordered_set<audio_format_t> formatSet;
7996 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7997 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007998 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007999 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008000 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008001 formatSet.insert(*formatIter);
8002 }
8003 }
8004 } else {
8005 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8006 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008007 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008008
jiabin81772902018-04-02 17:52:27 -07008009 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008010 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008011 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8012 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8013 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008014 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008015 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8016 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8017 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008018 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008019 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008020 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008021 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008022 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008023 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008024}
8025
jiabin06e4bab2019-07-29 10:13:34 -07008026void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8027 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008028 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8029 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8030
8031 // If NEVER, then remove support for channelMasks > stereo.
8032 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008033 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8034 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008035 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008036 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008037 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008038 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008039 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008040 }
8041 }
jiabin81772902018-04-02 17:52:27 -07008042 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8043 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8044 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008045 bool supports5dot1 = false;
8046 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008047 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008048 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8049 supports5dot1 = true;
8050 break;
8051 }
8052 }
8053 // If not then add 5.1 support.
8054 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008055 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008056 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008057 }
Phil Burk09bc4612016-02-24 15:58:15 -08008058 }
8059}
8060
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008061void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008062 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01008063 AudioProfileVector &profiles)
8064{
8065 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008066 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07008067
François Gaffie112b0af2015-11-19 16:13:25 +01008068 // Format MUST be checked first to update the list of AudioProfile
8069 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008070 reply = mpClientInterface->getParameters(
8071 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07008072 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008073 AudioParameter repliedParameters(reply);
8074 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008075 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01008076 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
8077 return;
8078 }
Phil Burk09bc4612016-02-24 15:58:15 -08008079 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01008080 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08008081 if (device == AUDIO_DEVICE_OUT_HDMI
8082 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008083 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07008084 }
jiabin3e277cc2019-09-10 14:27:34 -07008085 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01008086 }
François Gaffie112b0af2015-11-19 16:13:25 +01008087
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008088 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07008089 ChannelMaskSet channelMasks;
8090 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01008091 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07008092 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01008093
8094 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008095 reply = mpClientInterface->getParameters(
8096 ioHandle,
8097 requestedParameters.toString() + ";" +
8098 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01008099 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008100 AudioParameter repliedParameters(reply);
8101 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008102 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008103 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01008104 }
8105 }
8106 if (profiles.hasDynamicChannelsFor(format)) {
8107 reply = mpClientInterface->getParameters(ioHandle,
8108 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07008109 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01008110 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008111 AudioParameter repliedParameters(reply);
8112 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008113 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008114 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008115 if (device == AUDIO_DEVICE_OUT_HDMI
8116 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008117 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07008118 }
François Gaffie112b0af2015-11-19 16:13:25 +01008119 }
8120 }
jiabin3e277cc2019-09-10 14:27:34 -07008121 addDynamicAudioProfileAndSort(
8122 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01008123 }
8124}
Eric Laurentd60560a2015-04-10 11:31:20 -07008125
Mikhail Naganovdc769682018-05-04 15:34:08 -07008126status_t AudioPolicyManager::installPatch(const char *caller,
8127 audio_patch_handle_t *patchHandle,
8128 AudioIODescriptorInterface *ioDescriptor,
8129 const struct audio_patch *patch,
8130 int delayMs)
8131{
8132 ssize_t index = mAudioPatches.indexOfKey(
8133 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8134 *patchHandle : ioDescriptor->getPatchHandle());
8135 sp<AudioPatch> patchDesc;
8136 status_t status = installPatch(
8137 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8138 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008139 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008140 }
8141 return status;
8142}
8143
8144status_t AudioPolicyManager::installPatch(const char *caller,
8145 ssize_t index,
8146 audio_patch_handle_t *patchHandle,
8147 const struct audio_patch *patch,
8148 int delayMs,
8149 uid_t uid,
8150 sp<AudioPatch> *patchDescPtr)
8151{
8152 sp<AudioPatch> patchDesc;
8153 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8154 if (index >= 0) {
8155 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008156 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008157 }
8158
8159 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8160 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8161 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8162 if (status == NO_ERROR) {
8163 if (index < 0) {
8164 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008165 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008166 } else {
8167 patchDesc->mPatch = *patch;
8168 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008169 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008170 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008171 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008172 }
8173 nextAudioPortGeneration();
8174 mpClientInterface->onAudioPatchListUpdate();
8175 }
8176 if (patchDescPtr) *patchDescPtr = patchDesc;
8177 return status;
8178}
8179
jiabinbce0c1d2020-10-05 11:20:18 -07008180bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8181{
8182 const TrackClientVector activeClients = output->getActiveClients();
8183 if (activeClients.empty()) {
8184 return true;
8185 }
8186 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8187 if (index < 0) {
8188 ALOGE("%s, no audio patch found while there are active clients on output %d",
8189 __func__, output->getId());
8190 return false;
8191 }
8192 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8193 DeviceVector routedDevices;
8194 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8195 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8196 patchDesc->mPatch.sinks[i].id);
8197 if (device == nullptr) {
8198 ALOGE("%s, no audio device found with id(%d)",
8199 __func__, patchDesc->mPatch.sinks[i].id);
8200 return false;
8201 }
8202 routedDevices.add(device);
8203 }
8204 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008205 if (client->isInvalid()) {
8206 // No need to take care about invalidated clients.
8207 continue;
8208 }
jiabinbce0c1d2020-10-05 11:20:18 -07008209 sp<DeviceDescriptor> preferredDevice =
8210 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8211 if (mEngine->getOutputDevicesForAttributes(
8212 client->attributes(), preferredDevice, false) == routedDevices) {
8213 return false;
8214 }
8215 }
8216 return true;
8217}
8218
8219sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008220 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008221 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8222 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008223{
8224 for (const auto& device : devices) {
8225 // TODO: This should be checking if the profile supports the device combo.
8226 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008227 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8228 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008229 return nullptr;
8230 }
8231 }
8232 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8233 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008234 status_t status = desc->open(halConfig, mixerConfig, devices,
8235 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008236 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008237 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008238 return nullptr;
8239 }
8240
8241 // Here is where the out_set_parameters() for card & device gets called
8242 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8243 const audio_devices_t deviceType = device->type();
8244 const String8 &address = String8(device->address().c_str());
8245 if (!address.isEmpty()) {
8246 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8247 mpClientInterface->setParameters(output, String8(param));
8248 free(param);
8249 }
8250 updateAudioProfiles(device, output, profile->getAudioProfiles());
8251 if (!profile->hasValidAudioProfile()) {
8252 ALOGW("%s() missing param", __func__);
8253 desc->close();
8254 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008255 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8256 // Reopen the output with the best audio profile picked by APM when the profile supports
8257 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008258 desc->close();
8259 output = AUDIO_IO_HANDLE_NONE;
8260 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8261 profile->pickAudioProfile(
8262 config.sample_rate, config.channel_mask, config.format);
8263 config.offload_info.sample_rate = config.sample_rate;
8264 config.offload_info.channel_mask = config.channel_mask;
8265 config.offload_info.format = config.format;
8266
jiabina84c3d32022-12-02 18:59:55 +00008267 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008268 if (status != NO_ERROR) {
8269 return nullptr;
8270 }
8271 }
8272
8273 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008274
baek.kim -61c20122022-07-27 10:05:32 +00008275 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8276 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8277
jiabinbce0c1d2020-10-05 11:20:18 -07008278 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8279 sp<AudioPolicyMix> policyMix;
8280 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8281 policyMix->setOutput(desc);
8282 desc->mPolicyMix = policyMix;
8283 } else {
8284 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
8285 address.string());
8286 }
8287
baek.kim -61c20122022-07-27 10:05:32 +00008288 } else if (hasPrimaryOutput() && speaker != nullptr
8289 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008290 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8291 // no duplicated output for:
8292 // - direct outputs
8293 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008294 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008295 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8296
8297 //TODO: configure audio effect output stage here
8298
8299 // open a duplicating output thread for the new output and the primary output
8300 sp<SwAudioOutputDescriptor> dupOutputDesc =
8301 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8302 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8303 if (status == NO_ERROR) {
8304 // add duplicated output descriptor
8305 addOutput(duplicatedOutput, dupOutputDesc);
8306 } else {
8307 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8308 mPrimaryOutput->mIoHandle, output);
8309 desc->close();
8310 removeOutput(output);
8311 nextAudioPortGeneration();
8312 return nullptr;
8313 }
8314 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008315 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8316 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8317 mPrimaryOutput = desc;
8318 }
jiabinbce0c1d2020-10-05 11:20:18 -07008319 return desc;
8320}
8321
jiabinf1c73972022-04-14 16:28:52 -07008322status_t AudioPolicyManager::getDevicesForAttributes(
8323 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8324 // Devices are determined in the following precedence:
8325 //
8326 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8327 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8328 //
8329 // If no such dynamic policy then
8330 // 2) Devices containing an active client using setPreferredDevice
8331 // with same strategy as the attributes.
8332 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8333 //
8334 // If no corresponding active client with setPreferredDevice then
8335 // 3) Devices associated with the strategy determined by the attributes
8336 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8337 //
8338 // See related getOutputForAttrInt().
8339
8340 // check dynamic policies but only for primary descriptors (secondary not used for audible
8341 // audio routing, only used for duplication for playback capture)
8342 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008343 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008344 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008345 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8346 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8347 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008348 if (status != OK) {
8349 return status;
8350 }
8351
8352 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8353 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8354 // as they are unaffected by device/stream volume
8355 // (per SwAudioOutputDescriptor::isFixedVolume()).
8356 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8357 ) {
8358 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8359 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8360 devices.add(deviceDesc);
8361 } else {
8362 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8363 // which selects setPreferredDevice if active. This means forVolume call
8364 // will take an active setPreferredDevice, if such exists.
8365
8366 devices = mEngine->getOutputDevicesForAttributes(
8367 attr, nullptr /* preferredDevice */, false /* fromCache */);
8368 }
8369
8370 if (forVolume) {
8371 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8372 // for single volume control in AudioService (such relationship should exist if
8373 // SPEAKER_SAFE is present).
8374 //
8375 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8376 DeviceVector speakerSafeDevices =
8377 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8378 if (!speakerSafeDevices.isEmpty()) {
8379 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8380 devices.remove(speakerSafeDevices);
8381 }
8382 }
8383
8384 return NO_ERROR;
8385}
8386
8387status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8388 AudioProfileVector& audioProfiles,
8389 uint32_t flags,
8390 bool isInput) {
8391 for (const auto& hwModule : mHwModules) {
8392 // the MSD module checks for different conditions
8393 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8394 continue;
8395 }
8396 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8397 : hwModule->getOutputProfiles();
8398 for (const auto& profile : ioProfiles) {
8399 if (!profile->areAllDevicesSupported(devices) ||
8400 !profile->isCompatibleProfileForFlags(
8401 flags, false /*exactMatchRequiredForInputFlags*/)) {
8402 continue;
8403 }
8404 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8405 }
8406 }
8407
8408 if (!isInput) {
8409 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8410 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8411 if (msdModule != nullptr) {
8412 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8413 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8414 for (const auto &profile: msdModule->getOutputProfiles()) {
8415 if (!profile->asAudioPort()->isDirectOutput()) {
8416 continue;
8417 }
8418 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8419 }
8420 } else {
8421 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8422 }
8423 }
8424 }
8425
8426 return NO_ERROR;
8427}
8428
jiabin3ff8d7d2022-12-13 06:27:44 +00008429sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8430 const audio_config_t *config,
8431 audio_output_flags_t flags,
8432 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008433 closeOutput(outputDesc->mIoHandle);
8434 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8435 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8436 if (preferredOutput == nullptr) {
8437 ALOGE("%s failed to reopen output device=%d, caller=%s",
8438 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008439 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008440 return preferredOutput;
8441}
8442
8443void AudioPolicyManager::reopenOutputsWithDevices(
8444 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8445 for (const auto& [output, devices] : outputsToReopen) {
8446 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8447 closeOutput(output);
8448 openOutputWithProfileAndDevice(desc->mProfile, devices);
8449 }
jiabina84c3d32022-12-02 18:59:55 +00008450}
8451
jiabinc44b3462022-12-08 12:52:31 -08008452PortHandleVector AudioPolicyManager::getClientsForStream(
8453 audio_stream_type_t streamType) const {
8454 PortHandleVector clients;
8455 for (size_t i = 0; i < mOutputs.size(); ++i) {
8456 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8457 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8458 }
8459 return clients;
8460}
8461
8462void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8463 PortHandleVector clients;
8464 for (auto stream : streams) {
8465 PortHandleVector clientsForStream = getClientsForStream(stream);
8466 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8467 }
8468 mpClientInterface->invalidateTracks(clients);
8469}
8470
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008471} // namespace android