blob: d09e426821d3b5f5f2750b5206c4e16acd2b637b [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Eric Laurent16c66dd2019-05-01 17:54:10 -070032#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070033#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000034#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080036#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080037#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080038#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110039#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070040
41#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010042#include <android/media/audio/common/AudioPort.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070043#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070044#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070046#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070047#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070048#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070049#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070050#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070051#include <utils/Log.h>
52
Eric Laurentd4692962014-05-05 18:13:44 -070053#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010054#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070055
Eric Laurent3b73df72014-03-11 09:06:29 -070056namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070057
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010058using android::media::audio::common::AudioDevice;
59using android::media::audio::common::AudioDeviceAddress;
60using android::media::audio::common::AudioPortDeviceExt;
61using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000062using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070063
Eric Laurentdc462862016-07-19 12:29:53 -070064//FIXME: workaround for truncated touch sounds
65// to be removed when the problem is handled by system UI
66#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070067
68// Largest difference in dB on earpiece in call between the voice volume and another
69// media / notification / system volume.
70constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
71
jiabin06e4bab2019-07-29 10:13:34 -070072template <typename T>
73bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
74{
75 if (left.size() != right.size()) {
76 return false;
77 }
78 for (size_t index = 0; index < right.size(); index++) {
79 if (left[index] != right[index]) {
80 return false;
81 }
82 }
83 return true;
84}
85
86template <typename T>
87bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
88{
89 return !(left == right);
90}
91
Eric Laurente552edb2014-03-10 17:42:56 -070092// ----------------------------------------------------------------------------
93// AudioPolicyInterface implementation
94// ----------------------------------------------------------------------------
95
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010096status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
97 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
98 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -080099 nextAudioPortGeneration();
100 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800101}
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
104 audio_policy_dev_state_t state,
105 const char* device_address,
106 const char* device_name,
107 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800108 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100109 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
110 status == OK) {
111 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
112 } else {
113 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
114 return status;
115 }
116}
117
François Gaffie11d30102018-11-02 16:09:09 +0100118void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
119 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200120{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000121 audio_port_v7 devicePort;
122 device->toAudioPort(&devicePort);
123 if (status_t status = mpClientInterface->setDeviceConnectedState(
124 &devicePort, state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
125 status != OK) {
126 ALOGE("Error %d while setting connected state for device %s", status,
127 device->getDeviceTypeAddr().toString(false).c_str());
128 }
François Gaffie44481e72016-04-20 07:49:57 +0200129}
130
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100131status_t AudioPolicyManager::setDeviceConnectionStateInt(
132 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
133 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100134 if (port.ext.getTag() != AudioPortExt::device) {
135 return BAD_VALUE;
136 }
137 audio_devices_t device_type;
138 std::string device_address;
139 if (status_t status = aidl2legacy_AudioDevice_audio_device(
140 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
141 status != OK) {
142 return status;
143 };
144 const char* device_name = port.name.c_str();
145 // connect/disconnect only 1 device at a time
146 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
147 return BAD_VALUE;
148
149 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
150 device_type, device_address.c_str(), device_name, encodedFormat,
151 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000152 if (device == nullptr) {
153 return INVALID_OPERATION;
154 }
155 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
156 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
157 }
158 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100159}
160
François Gaffie11d30102018-11-02 16:09:09 +0100161status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800162 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100163 const char* device_address,
164 const char* device_name,
165 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800166 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100167 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
168 status == OK) {
169 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
170 } else {
171 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
172 return status;
173 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700174}
Paul McLeane743a472015-01-28 11:07:31 -0800175
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700176status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
177 audio_policy_dev_state_t state)
178{
Eric Laurente552edb2014-03-10 17:42:56 -0700179 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700180 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700181 SortedVector <audio_io_handle_t> outputs;
182
François Gaffie11d30102018-11-02 16:09:09 +0100183 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700184
Eric Laurente552edb2014-03-10 17:42:56 -0700185 // save a copy of the opened output descriptors before any output is opened or closed
186 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
187 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100188
189 bool wasLeUnicastActive = isLeUnicastActive();
190
Eric Laurente552edb2014-03-10 17:42:56 -0700191 switch (state)
192 {
193 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800194 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700195 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100196 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700197 return INVALID_OPERATION;
198 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800199 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700200 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700201
Eric Laurente552edb2014-03-10 17:42:56 -0700202 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200203 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700204 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700205 }
206
François Gaffie44481e72016-04-20 07:49:57 +0200207 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
208 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100209 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200210
François Gaffie11d30102018-11-02 16:09:09 +0100211 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
212 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200213
Francois Gaffie716e1432019-01-14 16:58:59 +0100214 mHwModules.cleanUpForDevice(device);
215
François Gaffie11d30102018-11-02 16:09:09 +0100216 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700217 return INVALID_OPERATION;
218 }
François Gaffie2110e042015-03-24 08:41:51 +0100219
jiabin1c4794b2020-05-05 10:08:05 -0700220 // Populate encapsulation information when a output device is connected.
221 device->setEncapsulationInfoFromHal(mpClientInterface);
222
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700223 // outputs should never be empty here
224 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
225 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100226 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800227
Eric Laurent3ae5f312015-02-03 17:12:08 -0800228 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700229 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700230 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700231 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100232 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700233 return INVALID_OPERATION;
234 }
235
François Gaffie11d30102018-11-02 16:09:09 +0100236 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700237
Paul McLeane743a472015-01-28 11:07:31 -0800238 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100239 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700240
Eric Laurente552edb2014-03-10 17:42:56 -0700241 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100242 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700243
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100244 mOutputs.clearSessionRoutesForDevice(device);
245
François Gaffie11d30102018-11-02 16:09:09 +0100246 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100247
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800248 // Reset active device codec
249 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
250
Kriti Dangef6be8f2020-11-05 11:58:19 +0100251 // remove device from mReportedFormatsMap cache
252 mReportedFormatsMap.erase(device);
253
jiabina84c3d32022-12-02 18:59:55 +0000254 // remove preferred mixer configurations
255 mPreferredMixerAttrInfos.erase(device->getId());
256
Eric Laurente552edb2014-03-10 17:42:56 -0700257 } break;
258
259 default:
François Gaffie11d30102018-11-02 16:09:09 +0100260 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700261 return BAD_VALUE;
262 }
263
Eric Laurent736a1022019-03-27 18:28:46 -0700264 // Propagate device availability to Engine
265 setEngineDeviceConnectionState(device, state);
266
Eric Laurentae970022019-01-29 14:25:04 -0800267 // No need to evaluate playback routing when connecting a remote submix
268 // output device used by a dynamic policy of type recorder as no
269 // playback use case is affected.
270 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700271 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800272 for (audio_io_handle_t output : outputs) {
273 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800274 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
275 if (policyMix != nullptr
276 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700277 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800278 doCheckForDeviceAndOutputChanges = false;
279 break;
280 }
281 }
282 }
283
284 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700285 // outputs must be closed after checkOutputForAllStrategies() is executed
286 if (!outputs.isEmpty()) {
287 for (audio_io_handle_t output : outputs) {
288 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100289 // close unused outputs after device disconnection or direct outputs that have
290 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200291 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200292 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
293 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200294 (desc->mDirectOpenCount == 0))
295 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
296 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200297 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700298 closeOutput(output);
299 }
Eric Laurente552edb2014-03-10 17:42:56 -0700300 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700301 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
302 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700303 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700304 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800305 };
306
307 if (doCheckForDeviceAndOutputChanges) {
308 checkForDeviceAndOutputChanges(checkCloseOutputs);
309 } else {
310 checkCloseOutputs();
311 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100312 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100313 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700314 const DeviceVector activeMediaDevices =
315 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000316 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700317 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700318 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530319 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
320 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100321 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700322 // do not force device change on duplicated output because if device is 0, it will
323 // also force a device 0 for the two outputs it is duplicated to which may override
324 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100325 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100326 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700327 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700328 // always force when disconnecting (a non-duplicated device)
329 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin3ff8d7d2022-12-13 06:27:44 +0000330 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
331 // If the device is using preferred mixer attributes, the output need to reopen
332 // with default configuration when the new selected devices are different from
333 // current routing devices
334 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
335 continue;
336 }
François Gaffie11d30102018-11-02 16:09:09 +0100337 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700338 }
jiabinbce0c1d2020-10-05 11:20:18 -0700339 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000340 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700341 desc->supportsDevicesForPlayback(activeMediaDevices)) {
342 // Reopen the output to query the dynamic profiles when there is not active
343 // clients or all active clients will be rerouted. Otherwise, set the flag
344 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
345 // can be reopened to query dynamic profiles when all clients are inactive.
346 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000347 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700348 } else {
349 desc->mPendingReopenToQueryProfiles = true;
350 }
351 }
352 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
353 // Clear the flag that previously set for re-querying profiles.
354 desc->mPendingReopenToQueryProfiles = false;
355 }
356 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000357 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700358
Eric Laurentd60560a2015-04-10 11:31:20 -0700359 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100360 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700361 }
362
Eric Laurent96d1dda2022-03-14 17:14:19 +0100363 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
364
Eric Laurent72aa32f2014-05-30 18:51:48 -0700365 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700366 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700367 } // end if is output device
368
Eric Laurente552edb2014-03-10 17:42:56 -0700369 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700370 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100371 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700372 switch (state)
373 {
374 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700375 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700376 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100377 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700378 return INVALID_OPERATION;
379 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700380
381 if (mAvailableInputDevices.add(device) < 0) {
382 return NO_MEMORY;
383 }
384
François Gaffie44481e72016-04-20 07:49:57 +0200385 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
386 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100387 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200388
Eric Laurent0dd51852019-04-19 18:18:58 -0700389 if (checkInputsForDevice(device, state) != NO_ERROR) {
390 mAvailableInputDevices.remove(device);
391
François Gaffie11d30102018-11-02 16:09:09 +0100392 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100393
394 mHwModules.cleanUpForDevice(device);
395
Eric Laurentd4692962014-05-05 18:13:44 -0700396 return INVALID_OPERATION;
397 }
398
Eric Laurentd4692962014-05-05 18:13:44 -0700399 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700400
401 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700402 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700403 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100404 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700405 return INVALID_OPERATION;
406 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700407
François Gaffie11d30102018-11-02 16:09:09 +0100408 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700409
410 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100411 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700412
François Gaffie11d30102018-11-02 16:09:09 +0100413 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700414
415 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100416
417 // remove device from mReportedFormatsMap cache
418 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700419 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700420
421 default:
François Gaffie11d30102018-11-02 16:09:09 +0100422 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700423 return BAD_VALUE;
424 }
425
Eric Laurent736a1022019-03-27 18:28:46 -0700426 // Propagate device availability to Engine
427 setEngineDeviceConnectionState(device, state);
428
Eric Laurent0dd51852019-04-19 18:18:58 -0700429 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700430 // As the input device list can impact the output device selection, update
431 // getDeviceForStrategy() cache
432 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700433
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100434 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200435 // Reconnect Audio Source
436 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
437 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
438 checkAudioSourceForAttributes(attributes);
439 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700440 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100441 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700442 }
443
Eric Laurentb52c1522014-05-20 11:27:36 -0700444 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700445 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700446 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700447
François Gaffie11d30102018-11-02 16:09:09 +0100448 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700449 return BAD_VALUE;
450}
451
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100452status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
453 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800454 media::AudioPortFw* aidlPort) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100455 DeviceDescriptorBase devDescr(device, device_address);
456 devDescr.setName(device_name);
457 return devDescr.writeToParcelable(aidlPort);
458}
459
Eric Laurent736a1022019-03-27 18:28:46 -0700460void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
461 audio_policy_dev_state_t state) {
462
463 // the Engine does not have to know about remote submix devices used by dynamic audio policies
464 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
465 return;
466 }
467 mEngine->setDeviceConnectionState(device, state);
468}
469
470
Eric Laurente0720872014-03-11 09:30:41 -0700471audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100472 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700473{
Eric Laurent634b7142016-04-20 13:48:02 -0700474 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800475 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
476 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700477 (strlen(device_address) != 0)/*matchAddress*/);
478
479 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100480 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700481 device, device_address);
482 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
483 }
François Gaffie53615e22015-03-19 09:24:12 +0100484
Eric Laurent3a4311c2014-03-17 12:00:47 -0700485 DeviceVector *deviceVector;
486
Eric Laurente552edb2014-03-10 17:42:56 -0700487 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700488 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700489 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700490 deviceVector = &mAvailableInputDevices;
491 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100492 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700493 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700494 }
Eric Laurent634b7142016-04-20 13:48:02 -0700495
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800496 return (deviceVector->getDevice(
497 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700498 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800499}
500
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800501status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
502 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800503 const char *device_name,
504 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800505{
506 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700507 String8 reply;
508 AudioParameter param;
509 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800510
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800511 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
512 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800513
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800514 // connect/disconnect only 1 device at a time
515 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
516
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800517 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700518 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800519 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520 // Nothing to do: device is not connected
521 return NO_ERROR;
522 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800523 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800524
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700525 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800526 // configure codecs.
527 // Handle two specific cases by sending a set parameter to
528 // configure A2DP codecs. No need to toggle device state.
529 // Case 1: A2DP active device switches from primary to primary
530 // module
531 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200532 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700533 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800534 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
535 if (availablePrimaryOutputDevices().contains(devDesc) &&
536 (module != 0 && module->getHandle() == primaryHandle)) {
537 reply = mpClientInterface->getParameters(
538 AUDIO_IO_HANDLE_NONE,
539 String8(AudioParameter::keyReconfigA2dpSupported));
540 AudioParameter repliedParameters(reply);
541 repliedParameters.getInt(
542 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
543 if (isReconfigA2dpSupported) {
544 const String8 key(AudioParameter::keyReconfigA2dp);
545 param.add(key, String8("true"));
546 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
547 devDesc->setEncodedFormat(encodedFormat);
548 return NO_ERROR;
549 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700550 }
551 }
cnx421bd2dcc42020-07-11 14:58:44 +0800552 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
553 for (size_t i = 0; i < mOutputs.size(); i++) {
554 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
555 // mute media strategies and delay device switch by the largest
556 // This avoid sending the music tail into the earpiece or headset.
557 setStrategyMute(musicStrategy, true, desc);
558 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
559 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
560 nullptr, true /*fromCache*/).types());
561 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800562 // Toggle the device state: UNAVAILABLE -> AVAILABLE
563 // This will force reading again the device configuration
564 status = setDeviceConnectionState(device,
565 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800566 device_address, device_name,
567 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800568 if (status != NO_ERROR) {
569 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
570 status);
571 return status;
572 }
573
574 status = setDeviceConnectionState(device,
575 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800576 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800577 if (status != NO_ERROR) {
578 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
579 status);
580 return status;
581 }
582
583 return NO_ERROR;
584}
585
Pattydd807582021-11-04 21:01:03 +0800586status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
587 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800588{
Pattydd807582021-11-04 21:01:03 +0800589 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800590 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800591 std::unordered_set<audio_format_t> formatSet;
592 sp<HwModule> primaryModule =
593 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700594 if (primaryModule == nullptr) {
595 ALOGE("%s() unable to get primary module", __func__);
596 return NO_INIT;
597 }
Pattydd807582021-11-04 21:01:03 +0800598
599 DeviceTypeSet audioDeviceSet;
600
601 switch(device) {
602 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
603 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
604 break;
605 case AUDIO_DEVICE_OUT_BLE_HEADSET:
606 audioDeviceSet = getAudioDeviceOutAllBleSet();
607 break;
608 default:
609 ALOGE("%s() device type 0x%08x not supported", __func__, device);
610 return BAD_VALUE;
611 }
612
jiabin9a3361e2019-10-01 09:38:30 -0700613 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800614 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800615 for (const auto& device : declaredDevices) {
616 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800617 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800618 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800619 return status;
620}
621
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100622DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
623{
624 DeviceVector rxSinkdevices{};
625 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
626 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
627 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
628 auto rxSinkDevice = rxSinkdevices.itemAt(0);
629 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
630 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
631 // retrieve Rx Source device descriptor
632 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
633 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
634
635 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
636 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
637 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
638 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
639 return DeviceVector(rxSinkDevice);
640 }
641 }
642 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
643 // the device returned is not necessarily reachable via this output
644 // (filter later by setOutputDevices())
645 return getNewOutputDevices(mPrimaryOutput, fromCache);
646}
647
648status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
649{
650 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
651 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
652 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
653 }
654 return INVALID_OPERATION;
655}
656
657status_t AudioPolicyManager::updateCallRoutingInternal(
658 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700659{
660 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100661 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700662 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700663 if(!hasPrimaryOutput() ||
664 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100665 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700666 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100667 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100668
Francois Gaffie716e1432019-01-14 16:58:59 +0100669 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100670 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100671 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100672
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100673 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100674 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700675
Francois Gaffie601801d2021-06-22 13:27:39 +0200676 disconnectTelephonyAudioSource(mCallRxSourceClient);
677 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700678
François Gaffie9eb18552018-11-05 10:33:26 +0100679 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700680 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100681 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700682 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100683 // retrieve Rx Source and Tx Sink device descriptors
684 sp<DeviceDescriptor> rxSourceDevice =
685 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
686 String8(),
687 AUDIO_FORMAT_DEFAULT);
688 sp<DeviceDescriptor> txSinkDevice =
689 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
690 String8(),
691 AUDIO_FORMAT_DEFAULT);
692
693 // RX and TX Telephony device are declared by Primary Audio HAL
694 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
695 (telephonyRxModule->getHalVersionMajor() >= 3)) {
696 if (rxSourceDevice == 0 || txSinkDevice == 0) {
697 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100698 ALOGE("%s() no telephony Tx and/or RX device", __func__);
699 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100700 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100701 // createAudioPatchInternal now supports both HW / SW bridging
702 createRxPatch = true;
703 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100704 } else {
705 // If the RX device is on the primary HW module, then use legacy routing method for
706 // voice calls via setOutputDevice() on primary output.
707 // Otherwise, create two audio patches for TX and RX path.
708 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
709 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700710 // If the TX device is also on the primary HW module, setOutputDevice() will take care
711 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100712 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
713 (txSinkDevice != 0);
714 }
715 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
716 // Otherwise, create two audio patches for TX and RX path.
717 if (!createRxPatch) {
718 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700719 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200720 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800721 // If the TX device is on the primary HW module but RX device is
722 // on other HW module, SinkMetaData of telephony input should handle it
723 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700724 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700725 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100726 // terminate active capture if on the same HW module as the call TX source device
727 // FIXME: would be better to refine to only inputs whose profile connects to the
728 // call TX device but this information is not in the audio patch and logic here must be
729 // symmetric to the one in startInput()
730 for (const auto& activeDesc : mInputs.getActiveInputs()) {
731 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
732 closeActiveClients(activeDesc);
733 }
734 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200735 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800736 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100737 if (waitMs != nullptr) {
738 *waitMs = muteWaitMs;
739 }
740 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800741}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700742
Mikhail Naganov100f0122018-11-29 11:22:16 -0800743bool AudioPolicyManager::isDeviceOfModule(
744 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
745 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
746 if (module != 0) {
747 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
748 .indexOf(devDesc) != NAME_NOT_FOUND
749 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
750 .indexOf(devDesc) != NAME_NOT_FOUND;
751 }
752 return false;
753}
754
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200755void AudioPolicyManager::connectTelephonyRxAudioSource()
756{
Francois Gaffie601801d2021-06-22 13:27:39 +0200757 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200758 const struct audio_port_config source = {
759 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
760 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
761 };
762 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200763 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
764 ALOGE_IF(mCallRxSourceClient == nullptr,
765 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200766}
767
Francois Gaffie601801d2021-06-22 13:27:39 +0200768void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200769{
Francois Gaffie601801d2021-06-22 13:27:39 +0200770 if (clientDesc == nullptr) {
771 return;
772 }
773 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
774 "%s error stopping audio source", __func__);
775 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200776}
777
778void AudioPolicyManager::connectTelephonyTxAudioSource(
779 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
780 uint32_t delayMs)
781{
Francois Gaffie601801d2021-06-22 13:27:39 +0200782 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200783 if (srcDevice == nullptr || sinkDevice == nullptr) {
784 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
785 return;
786 }
787 PatchBuilder patchBuilder;
788 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
789 ALOGV("%s between source %s and sink %s", __func__,
790 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200791 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200792 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
793
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200794 struct audio_port_config source = {};
795 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200796 mCallTxSourceClient = new InternalSourceClientDescriptor(
797 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200798 mCommunnicationStrategy, toVolumeSource(aa));
799 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
800 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200801 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
802 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200803 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
804 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200805 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200806 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200807}
808
Eric Laurente0720872014-03-11 09:30:41 -0700809void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700810{
811 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100812 // store previous phone state for management of sonification strategy below
813 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100814 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100815
816 if (mEngine->setPhoneState(state) != NO_ERROR) {
817 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700818 return;
819 }
François Gaffie2110e042015-03-24 08:41:51 +0100820 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700821 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700822 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700823 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800824 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700825 }
826
François Gaffie2110e042015-03-24 08:41:51 +0100827 /**
828 * Switching to or from incall state or switching between telephony and VoIP lead to force
829 * routing command.
830 */
Eric Laurent74b71512019-11-06 17:21:57 -0800831 bool force = ((isStateInCall(oldState) != isStateInCall(state))
832 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700833
834 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700835 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700836
Eric Laurente552edb2014-03-10 17:42:56 -0700837 int delayMs = 0;
838 if (isStateInCall(state)) {
839 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100840 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
841 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700842 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700843 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700844 // mute media and sonification strategies and delay device switch by the largest
845 // latency of any output where either strategy is active.
846 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100847 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
848 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
849 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700850 (delayMs < (int)desc->latency()*2)) {
851 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700852 }
François Gaffiec005e562018-11-06 15:04:49 +0100853 setStrategyMute(musicStrategy, true, desc);
854 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
855 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
856 nullptr, true /*fromCache*/).types());
857 setStrategyMute(sonificationStrategy, true, desc);
858 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
859 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
860 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700861 }
862 }
863
Eric Laurent87ffa392015-05-22 10:32:38 -0700864 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700865 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100866 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700867 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100868 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
869 // force routing command to audio hardware when ending call
870 // even if no device change is needed
871 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
872 rxDevices = mPrimaryOutput->devices();
873 }
874 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200875 disconnectTelephonyAudioSource(mCallRxSourceClient);
876 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100877 }
François Gaffie11d30102018-11-02 16:09:09 +0100878 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700879 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700880 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700881
jiabin3ff8d7d2022-12-13 06:27:44 +0000882 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700883 // reevaluate routing on all outputs in case tracks have been started during the call
884 for (size_t i = 0; i < mOutputs.size(); i++) {
885 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100886 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200887 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
888 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000889 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
890 // If the device is using preferred mixer attributes, the output need to reopen
891 // with default configuration when the new selected devices are different from
892 // current routing devices.
893 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
894 continue;
895 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200896 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
897 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700898 }
899 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000900 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700901
Eric Laurent96d1dda2022-03-14 17:14:19 +0100902 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
903
Eric Laurente552edb2014-03-10 17:42:56 -0700904 if (isStateInCall(state)) {
905 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700906 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800907 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700908 }
909
910 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100911 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
912 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700913}
914
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700915audio_mode_t AudioPolicyManager::getPhoneState() {
916 return mEngine->getPhoneState();
917}
918
Eric Laurente0720872014-03-11 09:30:41 -0700919void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100920 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700921{
François Gaffie2110e042015-03-24 08:41:51 +0100922 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700923 if (config == mEngine->getForceUse(usage)) {
924 return;
925 }
Eric Laurente552edb2014-03-10 17:42:56 -0700926
François Gaffie2110e042015-03-24 08:41:51 +0100927 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
928 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
929 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700930 }
François Gaffie2110e042015-03-24 08:41:51 +0100931 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
932 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
933 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700934
935 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700936 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800937
Eric Laurent22fcda22019-05-17 16:28:47 -0700938 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
939 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800940 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700941 }
942
Eric Laurentdc462862016-07-19 12:29:53 -0700943 //FIXME: workaround for truncated touch sounds
944 // to be removed when the problem is handled by system UI
945 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700946 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
947 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
948 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700949
950 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100951 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700952}
953
Eric Laurente0720872014-03-11 09:30:41 -0700954void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700955{
956 ALOGV("setSystemProperty() property %s, value %s", property, value);
957}
958
Dorin Drimusecc9f422022-03-09 17:57:40 +0100959// Find an MSD output profile compatible with the parameters passed.
960// When "directOnly" is set, restrict search to profiles for direct outputs.
961sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
962 const DeviceVector& devices,
963 uint32_t samplingRate,
964 audio_format_t format,
965 audio_channel_mask_t channelMask,
966 audio_output_flags_t flags,
967 bool directOnly)
968{
969 flags = getRelevantFlags(flags, directOnly);
970
971 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
972 if (msdModule != nullptr) {
973 // for the msd module check if there are patches to the output devices
974 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
975 HwModuleCollection modules;
976 modules.add(msdModule);
977 return searchCompatibleProfileHwModules(
978 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
979 flags, directOnly);
980 }
981 }
982 return nullptr;
983}
984
Michael Chana94fbb22018-04-24 14:31:19 +1000985// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
986// search to profiles for direct outputs.
987sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100988 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000989 uint32_t samplingRate,
990 audio_format_t format,
991 audio_channel_mask_t channelMask,
992 audio_output_flags_t flags,
993 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700994{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100995 flags = getRelevantFlags(flags, directOnly);
996
997 return searchCompatibleProfileHwModules(
998 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
999}
1000
1001audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1002 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001003 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001004 // only retain flags that will drive the direct output profile selection
1005 // if explicitly requested
1006 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001007 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001008 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1009 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001010 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001011 return flags;
1012}
Eric Laurent861a6282015-05-18 15:40:16 -07001013
Dorin Drimusecc9f422022-03-09 17:57:40 +01001014sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1015 const HwModuleCollection& hwModules,
1016 const DeviceVector& devices,
1017 uint32_t samplingRate,
1018 audio_format_t format,
1019 audio_channel_mask_t channelMask,
1020 audio_output_flags_t flags,
1021 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001022 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001023 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001024 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001025 if (!curProfile->isCompatibleProfile(devices,
1026 samplingRate, NULL /*updatedSamplingRate*/,
1027 format, NULL /*updatedFormat*/,
1028 channelMask, NULL /*updatedChannelMask*/,
1029 flags)) {
1030 continue;
1031 }
1032 // reject profiles not corresponding to a device currently available
1033 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1034 continue;
1035 }
1036 // reject profiles if connected device does not support codec
1037 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1038 continue;
1039 }
1040 if (!directOnly) {
1041 return curProfile;
1042 }
1043
1044 // when searching for direct outputs, if several profiles are compatible, give priority
1045 // to one with offload capability
1046 if (profile != 0 &&
1047 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001048 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001049 }
1050 profile = curProfile;
1051 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1052 break;
1053 }
Eric Laurente552edb2014-03-10 17:42:56 -07001054 }
1055 }
Eric Laurent861a6282015-05-18 15:40:16 -07001056 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001057}
1058
Eric Laurentfa0f6742021-08-17 18:39:44 +02001059sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001060 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001061{
1062 for (const auto& hwModule : mHwModules) {
1063 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001064 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001065 continue;
1066 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001067 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001068 // reject profiles not corresponding to a device currently available
1069 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1070 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1071 continue;
1072 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001073 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1074 != devices.size()) {
1075 continue;
1076 }
1077 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001078 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1079 return curProfile;
1080 }
1081 }
1082 return nullptr;
1083}
1084
Eric Laurentf4e63452017-11-06 19:31:46 +00001085audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001086{
François Gaffiec005e562018-11-06 15:04:49 +01001087 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001088
1089 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1090 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1091 // format, flags, etc. This may result in some discrepancy for functions that utilize
1092 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1093 // and AudioSystem::getOutputSamplingRate().
1094
François Gaffie11d30102018-11-02 16:09:09 +01001095 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001096 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001097
François Gaffie11d30102018-11-02 16:09:09 +01001098 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1099 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001100 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001101}
1102
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001103status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1104 const audio_attributes_t *srcAttr,
1105 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001106{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001107 if (srcAttr != NULL) {
1108 if (!isValidAttributes(srcAttr)) {
1109 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1110 __func__,
1111 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1112 srcAttr->tags);
1113 return BAD_VALUE;
1114 }
1115 *dstAttr = *srcAttr;
1116 } else {
1117 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1118 ALOGE("%s: invalid stream type", __func__);
1119 return BAD_VALUE;
1120 }
François Gaffiec005e562018-11-06 15:04:49 +01001121 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001122 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001123
1124 // Only honor audibility enforced when required. The client will be
1125 // forced to reconnect if the forced usage changes.
1126 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001127 dstAttr->flags = static_cast<audio_flags_mask_t>(
1128 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001129 }
1130
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001131 return NO_ERROR;
1132}
1133
Kevin Rocard153f92d2018-12-18 18:33:28 -08001134status_t AudioPolicyManager::getOutputForAttrInt(
1135 audio_attributes_t *resultAttr,
1136 audio_io_handle_t *output,
1137 audio_session_t session,
1138 const audio_attributes_t *attr,
1139 audio_stream_type_t *stream,
1140 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001141 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001142 audio_output_flags_t *flags,
1143 audio_port_handle_t *selectedDeviceId,
1144 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001145 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001146 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001147 bool *isSpatialized,
1148 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001149{
François Gaffiec005e562018-11-06 15:04:49 +01001150 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001151 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001152 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001153 const sp<DeviceDescriptor> requestedDevice =
1154 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1155
Eric Laurent8a1095a2019-11-08 14:44:16 -08001156 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001157 *isSpatialized = false;
1158
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001159 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1160 if (status != NO_ERROR) {
1161 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001162 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001163 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001164 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001165 }
François Gaffiec005e562018-11-06 15:04:49 +01001166 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001167
François Gaffiec005e562018-11-06 15:04:49 +01001168 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1169 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001170
Oscar Azucena873d10f2023-01-12 18:34:42 -08001171 bool usePrimaryOutputFromPolicyMixes = false;
1172
Kevin Rocard153f92d2018-12-18 18:33:28 -08001173 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1174 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1175 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001176 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001177 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1178 .channel_mask = config->channel_mask,
1179 .format = config->format,
1180 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001181 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001182 mAvailableOutputDevices, requestedDevice, primaryMix,
1183 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001184 if (status != OK) {
1185 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001186 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001187
Kevin Rocard153f92d2018-12-18 18:33:28 -08001188 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001189 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1190 && !audio_is_linear_pcm(config->format)) {
1191 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001192 return BAD_VALUE;
1193 }
1194 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001195 sp<DeviceDescriptor> deviceDesc =
1196 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1197 primaryMix->mDeviceAddress,
1198 AUDIO_FORMAT_DEFAULT);
1199 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001200 bool tryDirectForFlags = policyDesc == nullptr ||
1201 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1202 // if a direct output can be opened to deliver the track's multi-channel content to the
1203 // output rather than being downmixed by the primary output, then use this direct
1204 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1205 // mix.
1206 bool tryDirectForChannelMask = policyDesc != nullptr
1207 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1208 audio_channel_count_from_out_mask(config->channel_mask));
1209 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001210 audio_io_handle_t newOutput;
1211 status = openDirectOutput(
1212 *stream, session, config,
1213 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1214 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001215 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001216 policyDesc = mOutputs.valueFor(newOutput);
1217 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001218 } else if (tryDirectForFlags) {
1219 policyDesc = nullptr;
1220 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001221 }
1222 if (policyDesc != nullptr) {
1223 policyDesc->mPolicyMix = primaryMix;
1224 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001225 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001226
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001227 ALOGV("getOutputForAttr() returns output %d", *output);
1228 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1229 *outputType = API_OUT_MIX_PLAYBACK;
1230 } else {
1231 *outputType = API_OUTPUT_LEGACY;
1232 }
1233 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001234 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001235 }
François Gaffiec005e562018-11-06 15:04:49 +01001236 // Virtual sources must always be dynamicaly or explicitly routed
1237 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1238 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1239 return BAD_VALUE;
1240 }
1241 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1242 // in order to let the choice of the order to future vendor engine
1243 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001244
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001245 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001246 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001247 }
1248
Nadav Barb2f18162018-07-18 13:01:53 +03001249 // Set incall music only if device was explicitly set, and fallback to the device which is
1250 // chosen by the engine if not.
1251 // FIXME: provide a more generic approach which is not device specific and move this back
1252 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001253 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001254 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001255 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001256 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001257 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001258 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001259 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001260 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001261 }
1262 }
1263
François Gaffiec005e562018-11-06 15:04:49 +01001264 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1265 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1266 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001267
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001268 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001269 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001270 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001271 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001272 ALOGV("%s() Using MSD devices %s instead of devices %s",
1273 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001274 } else {
1275 *output = AUDIO_IO_HANDLE_NONE;
1276 }
1277 }
1278 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001279 sp<PreferredMixerAttributesInfo> info = nullptr;
1280 if (outputDevices.size() == 1) {
1281 info = getPreferredMixerAttributesInfo(
1282 outputDevices.itemAt(0)->getId(),
1283 mEngine->getProductStrategyForAttributes(*resultAttr));
jiabin5eaf0962022-12-20 20:11:38 +00001284 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1285 // and it is currently active.
1286 if (info != nullptr && info->getUid() != uid &&
1287 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1288 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001289 info = nullptr;
1290 }
1291 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001292 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001293 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001294 // The client will be active if the client is currently preferred mixer owner and the
1295 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001296 *isBitPerfect = (info != nullptr
1297 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001298 && info->getUid() == uid
1299 && *output != AUDIO_IO_HANDLE_NONE
1300 // When bit-perfect output is selected for the preferred mixer attributes owner,
1301 // only need to consider the config matches.
1302 && mOutputs.valueFor(*output)->isConfigurationMatched(
1303 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001304 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001305 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001306 AudioProfileVector profiles;
1307 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1308 if (ret == NO_ERROR && !profiles.empty()) {
1309 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
1310 : *profiles[0]->getChannels().begin();
1311 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
1312 : *profiles[0]->getSampleRates().begin();
1313 config->format = profiles[0]->getFormat();
1314 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001315 return INVALID_OPERATION;
1316 }
Paul McLeanaa981192015-03-21 09:55:15 -07001317
François Gaffiec005e562018-11-06 15:04:49 +01001318 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001319 for (auto &outputDevice : outputDevices) {
1320 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1321 *selectedDeviceId = outputDevice->getId();
1322 break;
1323 }
1324 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001325
Eric Laurent8a1095a2019-11-08 14:44:16 -08001326 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1327 *outputType = API_OUTPUT_TELEPHONY_TX;
1328 } else {
1329 *outputType = API_OUTPUT_LEGACY;
1330 }
1331
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001332 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1333
1334 return NO_ERROR;
1335}
1336
1337status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1338 audio_io_handle_t *output,
1339 audio_session_t session,
1340 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001341 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001342 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001343 audio_output_flags_t *flags,
1344 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001345 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001346 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001347 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001348 bool *isSpatialized,
1349 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001350{
1351 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1352 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1353 return INVALID_OPERATION;
1354 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001355 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001356 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001357 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001358 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001359 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001360 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001361 const sp<DeviceDescriptor> requestedDevice =
1362 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1363
1364 // Prevent from storing invalid requested device id in clients
1365 const audio_port_handle_t sanitizedRequestedPortId =
1366 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1367 *selectedDeviceId = sanitizedRequestedPortId;
1368
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001369 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001370 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001371 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1372 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001373 if (status != NO_ERROR) {
1374 return status;
1375 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001376 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001377 if (secondaryOutputs != nullptr) {
1378 for (auto &secondaryMix : secondaryMixes) {
1379 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1380 if (outputDesc != nullptr &&
1381 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1382 secondaryOutputs->push_back(outputDesc->mIoHandle);
1383 weakSecondaryOutputDescs.push_back(outputDesc);
1384 }
1385 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001386 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001387
Eric Laurent8fc147b2018-07-22 19:13:55 -07001388 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001389 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001390 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001391 };
jiabin4ef93452019-09-10 14:29:54 -07001392 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001393
Eric Laurentc209fe42020-06-05 18:11:23 -07001394 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001395 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001396 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001397 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001398 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001399 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001400 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001401 std::move(weakSecondaryOutputDescs),
1402 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001403 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001404
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001405 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1406 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001407
Eric Laurente83b55d2014-11-14 10:06:21 -08001408 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001409}
1410
Eric Laurentc529cf62020-04-17 18:19:10 -07001411status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1412 audio_session_t session,
1413 const audio_config_t *config,
1414 audio_output_flags_t flags,
1415 const DeviceVector &devices,
1416 audio_io_handle_t *output) {
1417
1418 *output = AUDIO_IO_HANDLE_NONE;
1419
1420 // skip direct output selection if the request can obviously be attached to a mixed output
1421 // and not explicitly requested
1422 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1423 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1424 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1425 return NAME_NOT_FOUND;
1426 }
1427
1428 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1429 // This prevents creating an offloaded track and tearing it down immediately after start
1430 // when audioflinger detects there is an active non offloadable effect.
1431 // FIXME: We should check the audio session here but we do not have it in this context.
1432 // This may prevent offloading in rare situations where effects are left active by apps
1433 // in the background.
1434 sp<IOProfile> profile;
1435 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1436 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1437 profile = getProfileForOutput(
1438 devices, config->sample_rate, config->format, config->channel_mask,
1439 flags, true /* directOnly */);
1440 }
1441
1442 if (profile == nullptr) {
1443 return NAME_NOT_FOUND;
1444 }
1445
1446 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1447 for (size_t i = 0; i < mOutputs.size(); i++) {
1448 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1449 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1450 // reuse direct output if currently open by the same client
1451 // and configured with same parameters
1452 if ((config->sample_rate == desc->getSamplingRate()) &&
1453 (config->format == desc->getFormat()) &&
1454 (config->channel_mask == desc->getChannelMask()) &&
1455 (session == desc->mDirectClientSession)) {
1456 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001457 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001458 mOutputs.keyAt(i), session);
1459 *output = mOutputs.keyAt(i);
1460 return NO_ERROR;
1461 }
1462 }
1463 }
1464
1465 if (!profile->canOpenNewIo()) {
1466 return NAME_NOT_FOUND;
1467 }
1468
1469 sp<SwAudioOutputDescriptor> outputDesc =
1470 new SwAudioOutputDescriptor(profile, mpClientInterface);
1471
Michael Chan6fb34492020-12-08 15:44:49 +11001472 // An MSD patch may be using the only output stream that can service this request. Release
1473 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001474 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001475
Eric Laurentf1f22e72021-07-13 14:04:14 +02001476 status_t status =
1477 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001478
1479 // only accept an output with the requested parameters
1480 if (status != NO_ERROR ||
1481 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1482 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1483 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1484 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1485 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1486 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1487 config->channel_mask, outputDesc->getChannelMask());
1488 if (*output != AUDIO_IO_HANDLE_NONE) {
1489 outputDesc->close();
1490 }
1491 // fall back to mixer output if possible when the direct output could not be open
1492 if (audio_is_linear_pcm(config->format) &&
1493 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1494 return NAME_NOT_FOUND;
1495 }
1496 *output = AUDIO_IO_HANDLE_NONE;
1497 return BAD_VALUE;
1498 }
1499 outputDesc->mDirectOpenCount = 1;
1500 outputDesc->mDirectClientSession = session;
1501
1502 addOutput(*output, outputDesc);
1503 mPreviousOutputs = mOutputs;
1504 ALOGV("%s returns new direct output %d", __func__, *output);
1505 mpClientInterface->onAudioPortListUpdate();
1506 return NO_ERROR;
1507}
1508
François Gaffie11d30102018-11-02 16:09:09 +01001509audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1510 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001511 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001512 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001513 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001514 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001515 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001516 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001517 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001518{
Andy Hungc88b0642018-04-27 15:42:35 -07001519 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001520
jiabine375d412019-02-26 12:54:53 -08001521 // Discard haptic channel mask when forcing muting haptic channels.
1522 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001523 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1524 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001525
Eric Laurente552edb2014-03-10 17:42:56 -07001526 // open a direct output if required by specified parameters
1527 //force direct flag if offload flag is set: offloading implies a direct output stream
1528 // and all common behaviors are driven by checking only the direct flag
1529 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001530 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1531 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001532 }
Nadav Bar766fb022018-01-07 12:18:03 +02001533 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1534 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001535 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001536
1537 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1538
Eric Laurente83b55d2014-11-14 10:06:21 -08001539 // only allow deep buffering for music stream type
1540 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001541 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001542 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001543 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001544 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1545 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001546 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001547 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001548 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001549 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001550 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001551 audio_is_linear_pcm(config->format) &&
1552 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001553 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001554 AUDIO_OUTPUT_FLAG_DIRECT);
1555 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001556 }
Eric Laurente552edb2014-03-10 17:42:56 -07001557
Carter Hsua3abb402021-10-26 11:11:20 +08001558 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1559 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1560 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1561 }
1562
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001563 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001564 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001565 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001566 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001567 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001568 }
1569
Eric Laurentc529cf62020-04-17 18:19:10 -07001570 audio_config_t directConfig = *config;
1571 directConfig.channel_mask = channelMask;
1572 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1573 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001574 return output;
1575 }
1576
Eric Laurent14cbfca2016-03-17 09:42:16 -07001577 // A request for HW A/V sync cannot fallback to a mixed output because time
1578 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001579 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001580 return AUDIO_IO_HANDLE_NONE;
1581 }
1582
Eric Laurente552edb2014-03-10 17:42:56 -07001583 // ignoring channel mask due to downmix capability in mixer
1584
1585 // open a non direct output
1586
1587 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001588 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001589 // get which output is suitable for the specified stream. The actual
1590 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001591 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001592 if (prefMixerConfigInfo != nullptr) {
1593 for (audio_io_handle_t outputHandle : outputs) {
1594 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1595 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1596 output = outputHandle;
1597 break;
1598 }
1599 }
1600 if (output == AUDIO_IO_HANDLE_NONE) {
1601 // No output open with the preferred profile. Open a new one.
1602 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1603 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1604 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1605 config.format = prefMixerConfigInfo->getConfigBase().format;
1606 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1607 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1608 &config, prefMixerConfigInfo->getFlags());
1609 if (preferredOutput == nullptr) {
1610 ALOGE("%s failed to open output with preferred mixer config", __func__);
1611 } else {
1612 output = preferredOutput->mIoHandle;
1613 }
1614 }
1615 } else {
1616 // at this stage we should ignore the DIRECT flag as no direct output could be
1617 // found earlier
1618 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1619 output = selectOutput(
1620 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1621 }
Eric Laurente552edb2014-03-10 17:42:56 -07001622 }
François Gaffie11d30102018-11-02 16:09:09 +01001623 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001624 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001625 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001626
Eric Laurente552edb2014-03-10 17:42:56 -07001627 return output;
1628}
1629
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001630sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001631 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1632 mAvailableInputDevices);
1633 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1634}
1635
1636DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1637 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1638 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001639}
1640
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001641const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001642 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001643 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1644 if (msdModule != 0) {
1645 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1646 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1647 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1648 const struct audio_port_config *source = &patch->mPatch.sources[j];
1649 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1650 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001651 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001652 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001653 }
1654 }
1655 }
1656 return msdPatches;
1657}
1658
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001659bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1660 ssize_t index = mAudioPatches.indexOfKey(handle);
1661 if (index < 0) {
1662 return false;
1663 }
1664 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1665 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1666 if (msdModule == nullptr) {
1667 return false;
1668 }
1669 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1670 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1671 return true;
1672 }
1673 index = getMsdOutputPatches().indexOfKey(handle);
1674 if (index < 0) {
1675 return false;
1676 }
1677 return true;
1678}
1679
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001680status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1681 const InputProfileCollection &inputProfiles,
1682 const OutputProfileCollection &outputProfiles,
1683 const sp<DeviceDescriptor> &sourceDevice,
1684 const sp<DeviceDescriptor> &sinkDevice,
1685 AudioProfileVector& sourceProfiles,
1686 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001687 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001688 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001689 return NO_INIT;
1690 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001691 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001692 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001693 return NO_INIT;
1694 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001695 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001696 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1697 inProfile->supportsDevice(sourceDevice)) {
1698 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001699 }
1700 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001701 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001702 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001703 outProfile->supportsDevice(sinkDevice)) {
1704 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001705 }
1706 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001707 return NO_ERROR;
1708}
1709
1710status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1711 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1712 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1713{
Dean Wheatley16809da2022-12-09 14:55:46 +11001714 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1715 static const std::vector<audio_format_t> formatsOrder = {{
1716 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1717 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1718 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1719 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1720 // preferred).
1721 std::vector<audio_channel_mask_t> masks = {{
1722 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1723 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1724 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1725 // insert index masks (higher counts most preferred) as preferred over position masks
1726 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1727 masks.insert(
1728 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1729 }
1730 return masks;
1731 }();
1732
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001733 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001734 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1735 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001736 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001737 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1738 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001739 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001740 }
1741 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1742 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1743 sinkConfig->format = bestSinkConfig.format;
1744 // For encoded streams force direct flag to prevent downstream mixing.
1745 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1746 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001747 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1748 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001749 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001750 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1751 // raw and IEC61937 framed streams.
1752 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1753 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1754 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001755 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1756 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001757 sourceConfig->channel_mask =
1758 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1759 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1760 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001761 sourceConfig->format = bestSinkConfig.format;
1762 // Copy input stream directly without any processing (e.g. resampling).
1763 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1764 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1765 if (hwAvSync) {
1766 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1767 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1768 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1769 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1770 }
1771 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1772 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1773 sinkConfig->config_mask |= config_mask;
1774 sourceConfig->config_mask |= config_mask;
1775 return NO_ERROR;
1776}
1777
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001778PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1779 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001780{
1781 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001782 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1783 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1784 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1785 if (deviceModule == nullptr) {
1786 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1787 return patchBuilder;
1788 }
1789 const InputProfileCollection inputProfiles = msdIsSource ?
1790 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1791 const OutputProfileCollection outputProfiles = msdIsSource ?
1792 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1793
1794 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1795 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1796 device : getMsdAudioOutDevices().itemAt(0);
1797 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1798
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001799 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1800 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001801 AudioProfileVector sourceProfiles;
1802 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001803 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1804 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001805 for (auto hwAvSync : { true, false }) {
1806 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1807 sourceProfiles, sinkProfiles) != NO_ERROR) {
1808 continue;
1809 }
1810 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1811 &sinkConfig) == NO_ERROR) {
1812 // Found a matching config. Re-create PatchBuilder with this config.
1813 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1814 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001815 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001816 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001817 " supporting PCM format conversion.", __func__);
1818 return patchBuilder;
1819}
1820
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001821status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001822 DeviceVector devices;
1823 if (outputDevices != nullptr && outputDevices->size() > 0) {
1824 devices.add(*outputDevices);
1825 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001826 // Use media strategy for unspecified output device. This should only
1827 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1828 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001829 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001830 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001831 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001832 }
Michael Chan6fb34492020-12-08 15:44:49 +11001833 std::vector<PatchBuilder> patchesToCreate;
1834 for (auto i = 0u; i < devices.size(); ++i) {
1835 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001836 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001837 }
1838 // Retain only the MSD patches associated with outputDevices request.
1839 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001840 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001841 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1842 auto retainedPatch = false;
1843 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1844 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1845 patchesToRemove.removeItemsAt(i);
1846 retainedPatch = true;
1847 break;
1848 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001849 }
Michael Chan6fb34492020-12-08 15:44:49 +11001850 if (retainedPatch) {
1851 it = patchesToCreate.erase(it);
1852 continue;
1853 }
1854 ++it;
1855 }
1856 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1857 return NO_ERROR;
1858 }
1859 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1860 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001861 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001862 }
Michael Chan6fb34492020-12-08 15:44:49 +11001863 status_t status = NO_ERROR;
1864 for (const auto &p : patchesToCreate) {
1865 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1866 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1867 char message[256];
1868 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1869 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1870 currStatus == NO_ERROR ? "Success" : "Error",
1871 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1872 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1873 if (currStatus == NO_ERROR) {
1874 ALOGD("%s", message);
1875 } else {
1876 ALOGE("%s", message);
1877 if (status == NO_ERROR) {
1878 status = currStatus;
1879 }
1880 }
1881 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001882 return status;
1883}
1884
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001885void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1886 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001887 for (size_t i = 0; i < msdPatches.size(); i++) {
1888 const auto& patch = msdPatches[i];
1889 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1890 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1891 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1892 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1893 releaseAudioPatch(patch->getHandle(), mUidCached);
1894 break;
1895 }
1896 }
1897 }
1898}
1899
Dorin Drimus94d94412022-02-02 09:05:02 +01001900bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1901 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1902 AudioPatchCollection msdPatches = getMsdOutputPatches();
1903 for (size_t i = 0; i < msdPatches.size(); i++) {
1904 const auto& patch = msdPatches[i];
1905 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1906 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1907 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1908 const auto& foundDevice = devicesToCheck.getDevice(
1909 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1910 if (foundDevice != nullptr) {
1911 devicesToCheck.remove(foundDevice);
1912 if (devicesToCheck.isEmpty()) {
1913 return true;
1914 }
1915 }
1916 }
1917 }
1918 }
1919 return false;
1920}
1921
Eric Laurente0720872014-03-11 09:30:41 -07001922audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001923 audio_output_flags_t flags,
1924 audio_format_t format,
1925 audio_channel_mask_t channelMask,
1926 uint32_t samplingRate,
1927 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001928{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001929 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1930 "%s called with format %#x", __func__, format);
1931
jiabinebb6af42020-06-09 17:31:17 -07001932 // Return the output that haptic-generating attached to when 1) session id is specified,
1933 // 2) haptic-generating effect exists for given session id and 3) the output that
1934 // haptic-generating effect attached to is in given outputs.
1935 if (sessionId != AUDIO_SESSION_NONE) {
1936 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1937 sessionId, FX_IID_HAPTICGENERATOR);
1938 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1939 return hapticGeneratingOutput;
1940 }
1941 }
1942
Eric Laurent16c66dd2019-05-01 17:54:10 -07001943 // Flags disqualifying an output: the match must happen before calling selectOutput()
1944 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1945 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1946
1947 // Flags expressing a functional request: must be honored in priority over
1948 // other criteria
1949 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1950 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001951 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1952 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001953 // Flags expressing a performance request: have lower priority than serving
1954 // requested sampling rate or channel mask
1955 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1956 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1957 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1958
1959 const audio_output_flags_t functionalFlags =
1960 (audio_output_flags_t)(flags & kFunctionalFlags);
1961 const audio_output_flags_t performanceFlags =
1962 (audio_output_flags_t)(flags & kPerformanceFlags);
1963
1964 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1965
Eric Laurente552edb2014-03-10 17:42:56 -07001966 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001967 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001968 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001969 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001970 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001971 // with tiebreak preferring the minimum number of extra functional flags
1972 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001973 // 3: the output supporting the exact channel mask
1974 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00001975 // 5: the output with the highest sampling rate if the requested sample rate is
1976 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001977 // 6: the output with the highest number of requested performance flags
1978 // 7: the output with the bit depth the closest to the requested one
1979 // 8: the primary output
1980 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001981
Eric Laurent16c66dd2019-05-01 17:54:10 -07001982 // matching criteria values in priority order for best matching output so far
1983 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001984
Eric Laurent16c66dd2019-05-01 17:54:10 -07001985 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1986 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1987 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001988
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001989 for (audio_io_handle_t output : outputs) {
1990 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001991 // matching criteria values in priority order for current output
1992 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001993
Eric Laurent16c66dd2019-05-01 17:54:10 -07001994 if (outputDesc->isDuplicated()) {
1995 continue;
1996 }
1997 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1998 continue;
1999 }
Eric Laurent8838a382014-09-08 16:44:28 -07002000
Eric Laurent16c66dd2019-05-01 17:54:10 -07002001 // If haptic channel is specified, use the haptic output if present.
2002 // When using haptic output, same audio format and sample rate are required.
2003 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002004 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002005 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2006 continue;
2007 }
2008 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002009 && format == outputDesc->getFormat()
2010 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002011 currentMatchCriteria[0] = outputHapticChannelCount;
2012 }
2013
2014 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002015 const int matchingFunctionalFlags =
2016 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2017 const int totalFunctionalFlags =
2018 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2019 // Prefer matching functional flags, but subtract unnecessary functional flags.
2020 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002021
2022 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002023 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2024 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002025 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2026 channelCount <= outputChannelCount) {
2027 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002028 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2029 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002030 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002031 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002032 currentMatchCriteria[3] = outputChannelCount;
2033 }
2034
2035 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002036 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002037 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002038 }
2039
2040 // performance flags match
2041 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2042
2043 // format match
2044 if (format != AUDIO_FORMAT_INVALID) {
2045 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002046 PolicyAudioPort::kFormatDistanceMax -
2047 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002048 }
2049
2050 // primary output match
2051 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2052
2053 // compare match criteria by priority then value
2054 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2055 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2056 bestMatchCriteria = currentMatchCriteria;
2057 bestOutput = output;
2058
2059 std::stringstream result;
2060 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2061 std::ostream_iterator<int>(result, " "));
2062 ALOGV("%s new bestOutput %d criteria %s",
2063 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002064 }
2065 }
2066
Eric Laurent16c66dd2019-05-01 17:54:10 -07002067 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002068}
2069
Eric Laurent8fc147b2018-07-22 19:13:55 -07002070status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002071{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002072 ALOGV("%s portId %d", __FUNCTION__, portId);
2073
2074 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2075 if (outputDesc == 0) {
2076 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002077 return BAD_VALUE;
2078 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002079 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002080
Eric Laurent8fc147b2018-07-22 19:13:55 -07002081 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002082 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002083
Eric Laurent733ce942017-12-07 12:18:25 -08002084 status_t status = outputDesc->start();
2085 if (status != NO_ERROR) {
2086 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002087 }
2088
Eric Laurent97ac8712018-07-27 18:59:02 -07002089 uint32_t delayMs;
2090 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002091
2092 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002093 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002094 if (status == DEAD_OBJECT) {
2095 sp<SwAudioOutputDescriptor> desc =
2096 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2097 if (desc == nullptr) {
2098 // This is not common, it may indicate something wrong with the HAL.
2099 ALOGE("%s unable to open output with default config", __func__);
2100 return status;
2101 }
2102 desc->mUsePreferredMixerAttributes = true;
2103 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002104 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002105 }
jiabina84c3d32022-12-02 18:59:55 +00002106
2107 // If the client is the first one active on preferred mixer parameters, reopen the output
2108 // if the current mixer parameters doesn't match the preferred one.
2109 if (outputDesc->devices().size() == 1) {
2110 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2111 outputDesc->devices()[0]->getId(), client->strategy());
2112 if (info != nullptr && info->getUid() == client->uid()) {
2113 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2114 info->getConfigBase(), info->getFlags())) {
2115 stopSource(outputDesc, client);
2116 outputDesc->stop();
2117 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2118 config.channel_mask = info->getConfigBase().channel_mask;
2119 config.sample_rate = info->getConfigBase().sample_rate;
2120 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002121 sp<SwAudioOutputDescriptor> desc =
2122 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2123 if (desc == nullptr) {
2124 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002125 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002126 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002127 // Intentionally return error to let the client side resending request for
2128 // creating and starting.
2129 return DEAD_OBJECT;
2130 }
2131 info->increaseActiveClient();
2132 }
2133 }
2134
Eric Laurentc75307b2015-03-17 15:29:32 -07002135 if (delayMs != 0) {
2136 usleep(delayMs * 1000);
2137 }
2138
2139 return status;
2140}
2141
Eric Laurent96d1dda2022-03-14 17:14:19 +01002142bool AudioPolicyManager::isLeUnicastActive() const {
2143 if (isInCall()) {
2144 return true;
2145 }
2146 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2147}
2148
2149bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2150 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2151 return false;
2152 }
2153 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2154 ALOGV("%s active %d", __func__, active);
2155 return active;
2156}
2157
Eric Laurent97ac8712018-07-27 18:59:02 -07002158status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2159 const sp<TrackClientDescriptor>& client,
2160 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002161{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002162 // cannot start playback of STREAM_TTS if any other output is being used
2163 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002164
2165 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002166 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002167 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002168 auto clientStrategy = client->strategy();
2169 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002170 if (stream == AUDIO_STREAM_TTS) {
2171 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002172 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002173 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002174 return INVALID_OPERATION;
2175 } else {
2176 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2177 }
2178 } else {
2179 // some playback other than beacon starts
2180 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2181 }
2182
Eric Laurent77305a62016-07-25 16:39:22 -07002183 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002184 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002185 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002186
François Gaffie11d30102018-11-02 16:09:09 +01002187 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002188 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002189 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002190 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002191 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002192 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002193 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002194 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002195 } else {
2196 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002197 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002198 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2199 AUDIO_FORMAT_DEFAULT);
2200 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2201 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002202 }
2203
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002204 // requiresMuteCheck is false when we can bypass mute strategy.
2205 // It covers a common case when there is no materially active audio
2206 // and muting would result in unnecessary delay and dropped audio.
2207 const uint32_t outputLatencyMs = outputDesc->latency();
2208 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002209 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002210
Eric Laurente552edb2014-03-10 17:42:56 -07002211 // increment usage count for this stream on the requested output:
2212 // NOTE that the usage count is the same for duplicated output and hardware output which is
2213 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002214 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002215
2216 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002217 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2218 client->isPreferredDeviceForExclusiveUse()) {
2219 // Preferred device may be exclusive, use only if no other active clients on this output
2220 devices = DeviceVector(
2221 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2222 } else {
2223 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2224 }
François Gaffie11d30102018-11-02 16:09:09 +01002225 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002226 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002227 }
2228 }
Eric Laurente552edb2014-03-10 17:42:56 -07002229
François Gaffiec005e562018-11-06 15:04:49 +01002230 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002231 selectOutputForMusicEffects();
2232 }
2233
François Gaffie1c878552018-11-22 16:53:21 +01002234 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002235 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002236 if (devices.isEmpty()) {
2237 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002238 }
François Gaffiec005e562018-11-06 15:04:49 +01002239 bool shouldWait =
2240 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2241 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2242 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002243 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002244 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002245 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002246 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002247 // An output has a shared device if
2248 // - managed by the same hw module
2249 // - supports the currently selected device
2250 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002251 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002252
Eric Laurent77305a62016-07-25 16:39:22 -07002253 // force a device change if any other output is:
2254 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002255 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002256 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002257 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002258 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002259 // change the device currently selected by the other output.
2260 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002261 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002262 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002263 force = true;
2264 }
2265 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002266 // a notification so that audio focus effect can propagate, or that a mute/unmute
2267 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002268 const uint32_t latencyMs = desc->latency();
2269 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2270
2271 if (shouldWait && isActive && (waitMs < latencyMs)) {
2272 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002273 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002274
2275 // Require mute check if another output is on a shared device
2276 // and currently active to have proper drain and avoid pops.
2277 // Note restoring AudioTracks onto this output needs to invoke
2278 // a volume ramp if there is no mute.
2279 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002280 }
2281 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002282
jiabin3ff8d7d2022-12-13 06:27:44 +00002283 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2284 // If the output is open with preferred mixer attributes, but the routed device is
2285 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2286 // changed.
2287 return DEAD_OBJECT;
2288 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002289 const uint32_t muteWaitMs =
jiabin3ff8d7d2022-12-13 06:27:44 +00002290 setOutputDevices(outputDesc, devices, force, 0, nullptr, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002291
Eric Laurente552edb2014-03-10 17:42:56 -07002292 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002293 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002294 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002295 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002296 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002297 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002298 outputDesc->useHwGain() /*force*/)) {
2299 // request AudioService to reinitialize the volume curves asynchronously
2300 ALOGE("checkAndSetVolume failed, requesting volume range init");
2301 mpClientInterface->onVolumeRangeInitRequest();
2302 };
Eric Laurente552edb2014-03-10 17:42:56 -07002303
2304 // update the outputs if starting an output with a stream that can affect notification
2305 // routing
2306 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002307
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002308 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002309 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002310 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002311 }
Eric Laurentdc462862016-07-19 12:29:53 -07002312
2313 if (waitMs > muteWaitMs) {
2314 *delayMs = waitMs - muteWaitMs;
2315 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002316
2317 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2318 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2319 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2320 // change occurs after the MixerThread starts and causes a stream volume
2321 // glitch.
2322 //
2323 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002324 }
Eric Laurentdc462862016-07-19 12:29:53 -07002325
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002326 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002327 mEngine->getForceUse(
2328 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002329 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002330 }
2331
Eric Laurent97ac8712018-07-27 18:59:02 -07002332 // Automatically enable the remote submix input when output is started on a re routing mix
2333 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002334 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2335 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002336 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2337 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2338 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002339 "remote-submix",
2340 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002341 }
2342
Eric Laurent96d1dda2022-03-14 17:14:19 +01002343 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2344
Eric Laurente552edb2014-03-10 17:42:56 -07002345 return NO_ERROR;
2346}
2347
Eric Laurent96d1dda2022-03-14 17:14:19 +01002348void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2349 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2350 bool isUnicastActive = isLeUnicastActive();
2351
2352 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002353 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002354 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2355 for (size_t i = 0; i < mOutputs.size(); i++) {
2356 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2357 if (desc != ignoredOutput && desc->isActive()
2358 && ((isUnicastActive &&
2359 !desc->devices().
2360 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2361 || (wasUnicastActive &&
2362 !desc->devices().getDevicesFromTypes(
2363 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2364 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2365 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002366 if (desc->mUsePreferredMixerAttributes && force) {
2367 // If the device is using preferred mixer attributes, the output need to reopen
2368 // with default configuration when the new selected devices are different from
2369 // current routing devices.
2370 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2371 continue;
2372 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002373 setOutputDevices(desc, newDevices, force, delayMs);
2374 // re-apply device specific volume if not done by setOutputDevice()
2375 if (!force) {
2376 applyStreamVolumes(desc, newDevices.types(), delayMs);
2377 }
2378 }
2379 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002380 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002381 }
2382}
2383
Eric Laurent8fc147b2018-07-22 19:13:55 -07002384status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002385{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002386 ALOGV("%s portId %d", __FUNCTION__, portId);
2387
2388 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2389 if (outputDesc == 0) {
2390 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002391 return BAD_VALUE;
2392 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002393 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002394
Eric Laurent97ac8712018-07-27 18:59:02 -07002395 ALOGV("stopOutput() output %d, stream %d, session %d",
2396 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002397
Eric Laurent97ac8712018-07-27 18:59:02 -07002398 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002399
Eric Laurent733ce942017-12-07 12:18:25 -08002400 if (status == NO_ERROR ) {
2401 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002402 } else {
2403 return status;
2404 }
2405
2406 if (outputDesc->devices().size() == 1) {
2407 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2408 outputDesc->devices()[0]->getId(), client->strategy());
2409 if (info != nullptr && info->getUid() == client->uid()) {
2410 info->decreaseActiveClient();
2411 if (info->getActiveClientCount() == 0) {
2412 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2413 }
2414 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002415 }
2416 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002417}
2418
Eric Laurent97ac8712018-07-27 18:59:02 -07002419status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2420 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002421{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002422 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002423 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002424 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002425 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002426
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002427 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2428
François Gaffie1c878552018-11-22 16:53:21 +01002429 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2430 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002431 // Automatically disable the remote submix input when output is stopped on a
2432 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002433 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002434 if (isSingleDeviceType(
2435 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002436 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002437 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002438 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2439 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002440 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002441 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002442 }
2443 }
2444 bool forceDeviceUpdate = false;
2445 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002446 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002447 forceDeviceUpdate = true;
2448 }
2449
Eric Laurente552edb2014-03-10 17:42:56 -07002450 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002451 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002452
Eric Laurente552edb2014-03-10 17:42:56 -07002453 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002454 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002455 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002456 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002457
2458 // If the routing does not change, if an output is routed on a device using HwGain
2459 // (aka setAudioPortConfig) and there are still active clients following different
2460 // volume group(s), force reapply volume
2461 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2462 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2463
Eric Laurente552edb2014-03-10 17:42:56 -07002464 // delay the device switch by twice the latency because stopOutput() is executed when
2465 // the track stop() command is received and at that time the audio track buffer can
2466 // still contain data that needs to be drained. The latency only covers the audio HAL
2467 // and kernel buffers. Also the latency does not always include additional delay in the
2468 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002469 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2470 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002471
2472 // force restoring the device selection on other active outputs if it differs from the
2473 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002474 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002475 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002476 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002477 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002478 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002479 desc->isActive() &&
2480 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002481 (newDevices != desc->devices())) {
2482 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2483 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002484
jiabin3ff8d7d2022-12-13 06:27:44 +00002485 if (desc->mUsePreferredMixerAttributes && force) {
2486 // If the device is using preferred mixer attributes, the output need to
2487 // reopen with default configuration when the new selected devices are
2488 // different from current routing devices.
2489 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2490 continue;
2491 }
François Gaffie11d30102018-11-02 16:09:09 +01002492 setOutputDevices(desc, newDevices2, force, delayMs);
2493
Eric Laurent57de36c2016-09-28 16:59:11 -07002494 // re-apply device specific volume if not done by setOutputDevice()
2495 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002496 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002497 }
Eric Laurente552edb2014-03-10 17:42:56 -07002498 }
2499 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002500 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002501 // update the outputs if stopping one with a stream that can affect notification routing
2502 handleNotificationRoutingForStream(stream);
2503 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002504
2505 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2506 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002507 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002508 }
2509
François Gaffiec005e562018-11-06 15:04:49 +01002510 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002511 selectOutputForMusicEffects();
2512 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002513
2514 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2515
Eric Laurente552edb2014-03-10 17:42:56 -07002516 return NO_ERROR;
2517 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002518 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002519 return INVALID_OPERATION;
2520 }
2521}
2522
jiabinbce0c1d2020-10-05 11:20:18 -07002523bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002524{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002525 ALOGV("%s portId %d", __FUNCTION__, portId);
2526
2527 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2528 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002529 // If an output descriptor is closed due to a device routing change,
2530 // then there are race conditions with releaseOutput from tracks
2531 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2532 // destroyed shortly thereafter.
2533 //
2534 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002535 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002536 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002537 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002538
2539 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002540
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302541 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2542 if (outputDesc->isClientActive(client)) {
2543 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2544 stopOutput(portId);
2545 }
2546
Eric Laurent8fc147b2018-07-22 19:13:55 -07002547 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2548 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002549 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002550 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002551 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002552 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002553 if (--outputDesc->mDirectOpenCount == 0) {
2554 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002555 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002556 }
2557 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302558
Andy Hung39efb7a2018-09-26 15:39:28 -07002559 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002560 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2561 // The output is pending reopened to query dynamic profiles and
2562 // there is no active clients
2563 closeOutput(outputDesc->mIoHandle);
2564 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2565 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2566 if (newOutputDesc == nullptr) {
2567 ALOGE("%s failed to open output", __func__);
2568 }
2569 return true;
2570 }
2571 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002572}
2573
Eric Laurentcaf7f482014-11-25 17:50:47 -08002574status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2575 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002576 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002577 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002578 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002579 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002580 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002581 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002582 input_type_t *inputType,
2583 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002584{
François Gaffiec005e562018-11-06 15:04:49 +01002585 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002586 "flags %#x attributes=%s requested device ID %d",
2587 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2588 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002589
Eric Laurentad2e7b92017-09-14 20:06:42 -07002590 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002591 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002592 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002593 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002594 sp<AudioInputDescriptor> inputDesc;
2595 sp<RecordClientDescriptor> clientDesc;
2596 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002597 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002598 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002599
2600 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2601 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2602 return INVALID_OPERATION;
2603 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002604
Francois Gaffie716e1432019-01-14 16:58:59 +01002605 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2606 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002607 }
2608
Paul McLean466dc8e2015-04-17 13:15:36 -06002609 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002610 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002611 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002612
Eric Laurentad2e7b92017-09-14 20:06:42 -07002613 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2614 // possible
2615 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2616 *input != AUDIO_IO_HANDLE_NONE) {
2617 ssize_t index = mInputs.indexOfKey(*input);
2618 if (index < 0) {
2619 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2620 status = BAD_VALUE;
2621 goto error;
2622 }
2623 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002624 RecordClientVector clients = inputDesc->getClientsForSession(session);
2625 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002626 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2627 status = BAD_VALUE;
2628 goto error;
2629 }
2630 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2631 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002632 // corresponds to a new client and is only permitted from the same UID.
2633 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002634 if (clients.size() > 1) {
2635 for (const auto& client : clients) {
2636 // The client map is ordered by key values (portId) and portIds are allocated
2637 // incrementaly. So the first client in this list is the one opened by audio flinger
2638 // when the mmap stream is created and should be ignored as it does not correspond
2639 // to an actual client
2640 if (client == *clients.cbegin()) {
2641 continue;
2642 }
2643 if (uid != client->uid() && !client->isSilenced()) {
2644 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2645 uid, client->portId(), client->uid());
2646 status = INVALID_OPERATION;
2647 goto error;
2648 }
Eric Laurent331679c2018-04-16 17:03:16 -07002649 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002650 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002651 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002652 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002653
Eric Laurentfecbceb2021-02-09 14:46:43 +01002654 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002655 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002656 }
2657
2658 *input = AUDIO_IO_HANDLE_NONE;
2659 *inputType = API_INPUT_INVALID;
2660
Francois Gaffie716e1432019-01-14 16:58:59 +01002661 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002662 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002663 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002664 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002665 ALOGW("%s could not find input mix for attr %s",
2666 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002667 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002668 }
jiabinc1de2df2019-05-07 14:26:40 -07002669 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2670 String8(attr->tags + strlen("addr=")),
2671 AUDIO_FORMAT_DEFAULT);
2672 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002673 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002674 __func__, attributes.source, attributes.tags);
2675 status = BAD_VALUE;
2676 goto error;
2677 }
2678
Kevin Rocard25f9b052019-02-27 15:08:54 -08002679 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2680 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2681 } else {
2682 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2683 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002684 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002685 if (explicitRoutingDevice != nullptr) {
2686 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002687 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002688 // Prevent from storing invalid requested device id in clients
2689 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002690 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002691 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2692 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002693 }
François Gaffie11d30102018-11-02 16:09:09 +01002694 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002695 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002696 status = BAD_VALUE;
2697 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002698 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002699 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2700 *inputType = API_INPUT_MIX_CAPTURE;
2701 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002702 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2703 // there is an external policy, but this input is attached to a mix of recorders,
2704 // meaning it receives audio injected into the framework, so the recorder doesn't
2705 // know about it and is therefore considered "legacy"
2706 *inputType = API_INPUT_LEGACY;
2707 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002708 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002709 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002710 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002711 } else {
2712 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002713 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002714
Eric Laurent599c7582015-12-07 18:05:55 -08002715 }
2716
François Gaffiec005e562018-11-06 15:04:49 +01002717 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002718 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002719 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002720 AudioProfileVector profiles;
2721 status_t ret = getProfilesForDevices(
2722 DeviceVector(device), profiles, flags, true /*isInput*/);
2723 if (ret == NO_ERROR && !profiles.empty()) {
2724 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
2725 : *profiles[0]->getChannels().begin();
2726 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
2727 : *profiles[0]->getSampleRates().begin();
2728 config->format = profiles[0]->getFormat();
2729 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002730 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002731 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002732
Eric Laurent8f42ea12018-08-08 09:08:25 -07002733exit:
2734
François Gaffiec005e562018-11-06 15:04:49 +01002735 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2736 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002737
Francois Gaffie716e1432019-01-14 16:58:59 +01002738 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002739 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002740 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002741
Mikhail Naganov2996f672019-04-18 12:29:59 -07002742 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002743 requestedDeviceId, attributes.source, flags,
2744 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002745 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002746 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002747
2748 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2749 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002750
Eric Laurent599c7582015-12-07 18:05:55 -08002751 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002752
2753error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002754 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002755}
2756
2757
François Gaffie11d30102018-11-02 16:09:09 +01002758audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002759 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002760 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002761 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002762 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002763 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002764{
2765 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002766 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002767 bool isSoundTrigger = false;
2768
François Gaffiec005e562018-11-06 15:04:49 +01002769 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002770 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2771 if (index >= 0) {
2772 input = mSoundTriggerSessions.valueFor(session);
2773 isSoundTrigger = true;
2774 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2775 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2776 } else {
2777 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002778 }
François Gaffiec005e562018-11-06 15:04:49 +01002779 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002780 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002781 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002782 }
2783
Carter Hsua3abb402021-10-26 11:11:20 +08002784 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2785 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2786 }
2787
Eric Laurentfe231122017-11-17 17:48:06 -08002788 // sampling rate and flags may be updated by getInputProfile
2789 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2790 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002791 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002792 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002793 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002794 // find a compatible input profile (not necessarily identical in parameters)
2795 sp<IOProfile> profile = getInputProfile(
2796 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2797 if (profile == nullptr) {
2798 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002799 }
jiabin2fd710d2022-05-02 23:20:22 +00002800
Glenn Kasten05ddca52016-02-11 08:17:12 -08002801 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002802 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002803 if (samplingRate == 0) {
2804 samplingRate = profileSamplingRate;
2805 }
Eric Laurente552edb2014-03-10 17:42:56 -07002806
Eric Laurent322b4d22015-04-03 15:57:54 -07002807 if (profile->getModuleHandle() == 0) {
2808 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002809 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002810 }
2811
Eric Laurentec376dc2021-04-08 20:41:22 +02002812 // Reuse an already opened input if a client with the same session ID already exists
2813 // on that input
2814 for (size_t i = 0; i < mInputs.size(); i++) {
2815 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2816 if (desc->mProfile != profile) {
2817 continue;
2818 }
2819 RecordClientVector clients = desc->clientsList();
2820 for (const auto &client : clients) {
2821 if (session == client->session()) {
2822 return desc->mIoHandle;
2823 }
2824 }
2825 }
2826
Eric Laurent3974e3b2017-12-07 17:58:43 -08002827 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002828 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002829 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002830 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002831 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002832 continue;
2833 }
2834 // if sound trigger, reuse input if used by other sound trigger on same session
2835 // else
2836 // reuse input if active client app is not in IDLE state
2837 //
2838 RecordClientVector clients = desc->clientsList();
2839 bool doClose = false;
2840 for (const auto& client : clients) {
2841 if (isSoundTrigger != client->isSoundTrigger()) {
2842 continue;
2843 }
2844 if (client->isSoundTrigger()) {
2845 if (session == client->session()) {
2846 return desc->mIoHandle;
2847 }
2848 continue;
2849 }
2850 if (client->active() && client->appState() != APP_STATE_IDLE) {
2851 return desc->mIoHandle;
2852 }
2853 doClose = true;
2854 }
2855 if (doClose) {
2856 closeInput(desc->mIoHandle);
2857 } else {
2858 i++;
2859 }
2860 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002861 }
2862
Eric Laurentfe231122017-11-17 17:48:06 -08002863 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002864
Eric Laurentfe231122017-11-17 17:48:06 -08002865 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2866 lConfig.sample_rate = profileSamplingRate;
2867 lConfig.channel_mask = profileChannelMask;
2868 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002869
François Gaffie11d30102018-11-02 16:09:09 +01002870 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002871
2872 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002873 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002874 (profileSamplingRate != lConfig.sample_rate) ||
2875 !audio_formats_match(profileFormat, lConfig.format) ||
2876 (profileChannelMask != lConfig.channel_mask)) {
2877 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002878 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002879 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002880 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002881 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002882 }
Eric Laurent599c7582015-12-07 18:05:55 -08002883 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002884 }
2885
Eric Laurentc722f302014-12-10 11:21:49 -08002886 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002887
Eric Laurent599c7582015-12-07 18:05:55 -08002888 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002889 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002890
Eric Laurent599c7582015-12-07 18:05:55 -08002891 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002892}
2893
Eric Laurent4eb58f12018-12-07 16:41:02 -08002894status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002895{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002896 ALOGV("%s portId %d", __FUNCTION__, portId);
2897
2898 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2899 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002900 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002901 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002902 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002903 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002904 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002905 if (client->active()) {
2906 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2907 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002908 }
2909
Eric Laurent8f42ea12018-08-08 09:08:25 -07002910 audio_session_t session = client->session();
2911
Eric Laurent4eb58f12018-12-07 16:41:02 -08002912 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002913
Eric Laurent4eb58f12018-12-07 16:41:02 -08002914 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002915
Eric Laurent4eb58f12018-12-07 16:41:02 -08002916 status_t status = inputDesc->start();
2917 if (status != NO_ERROR) {
2918 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002919 }
Eric Laurente552edb2014-03-10 17:42:56 -07002920
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002921 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002922 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002923 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002924
Eric Laurent8f42ea12018-08-08 09:08:25 -07002925 // indicate active capture to sound trigger service if starting capture from a mic on
2926 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002927 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002928 if (device != nullptr) {
2929 status = setInputDevice(input, device, true /* force */);
2930 } else {
2931 ALOGW("%s no new input device can be found for descriptor %d",
2932 __FUNCTION__, inputDesc->getId());
2933 status = BAD_VALUE;
2934 }
Eric Laurente552edb2014-03-10 17:42:56 -07002935
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002936 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002937 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002938 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002939 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002940 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2941 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002942 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002943 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002944
François Gaffie11d30102018-11-02 16:09:09 +01002945 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2946 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002947 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002948 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002949 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002950
Eric Laurent8f42ea12018-08-08 09:08:25 -07002951 // automatically enable the remote submix output when input is started if not
2952 // used by a policy mix of type MIX_TYPE_RECORDERS
2953 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002954 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002955 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002956 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002957 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002958 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2959 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002960 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002961 if (address != "") {
2962 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2963 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002964 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002965 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002966 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002967 } else if (status != NO_ERROR) {
2968 // Restore client activity state.
2969 inputDesc->setClientActive(client, false);
2970 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002971 }
2972
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002973 ALOGV("%s input %d source = %d status = %d exit",
2974 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002975
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002976 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002977}
2978
Eric Laurent8fc147b2018-07-22 19:13:55 -07002979status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002980{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002981 ALOGV("%s portId %d", __FUNCTION__, portId);
2982
2983 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2984 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002985 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002986 return BAD_VALUE;
2987 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002988 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002989 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002990 if (!client->active()) {
2991 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002992 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002993 }
Carter Hsue6139d52021-07-08 10:30:20 +08002994 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002995 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002996
Eric Laurent8f42ea12018-08-08 09:08:25 -07002997 inputDesc->stop();
2998 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002999 auto current_source = inputDesc->source();
3000 setInputDevice(input, getNewInputDevice(inputDesc),
3001 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003002 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003003 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003004 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003005 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003006 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3007 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003008 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003009 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003010
3011 // automatically disable the remote submix output when input is stopped if not
3012 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003013 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003014 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003015 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003016 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003017 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3018 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003019 }
3020 if (address != "") {
3021 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3022 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003023 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003024 }
3025 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003026 resetInputDevice(input);
3027
3028 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3029 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003030 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3031 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003032 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003033 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003034 }
3035 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003036 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003037 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003038}
3039
Eric Laurent8fc147b2018-07-22 19:13:55 -07003040void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003041{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003042 ALOGV("%s portId %d", __FUNCTION__, portId);
3043
3044 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3045 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003046 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003047 return;
3048 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003049 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003050 audio_io_handle_t input = inputDesc->mIoHandle;
3051
Eric Laurent8f42ea12018-08-08 09:08:25 -07003052 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003053
Andy Hung39efb7a2018-09-26 15:39:28 -07003054 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08003055
Andy Hung39efb7a2018-09-26 15:39:28 -07003056 if (inputDesc->getClientCount() > 0) {
3057 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003058 return;
3059 }
3060
Eric Laurent05b90f82014-08-27 15:32:29 -07003061 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003062 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003063 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003064}
3065
Eric Laurent8f42ea12018-08-08 09:08:25 -07003066void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003067{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003068 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003069
3070 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003071 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003072 }
3073}
3074
Eric Laurent8f42ea12018-08-08 09:08:25 -07003075void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3076{
3077 stopInput(portId);
3078 releaseInput(portId);
3079}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003080
Eric Laurent0dd51852019-04-19 18:18:58 -07003081void AudioPolicyManager::checkCloseInputs() {
3082 // After connecting or disconnecting an input device, close input if:
3083 // - it has no client (was just opened to check profile) OR
3084 // - none of its supported devices are connected anymore OR
3085 // - one of its clients cannot be routed to one of its supported
3086 // devices anymore. Otherwise update device selection
3087 std::vector<audio_io_handle_t> inputsToClose;
3088 for (size_t i = 0; i < mInputs.size(); i++) {
3089 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3090 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003091 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003092 inputsToClose.push_back(mInputs.keyAt(i));
3093 } else {
3094 bool close = false;
3095 for (const auto& client : input->clientsList()) {
3096 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003097 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3098 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003099 if (!input->supportedDevices().contains(device)) {
3100 close = true;
3101 break;
3102 }
3103 }
3104 if (close) {
3105 inputsToClose.push_back(mInputs.keyAt(i));
3106 } else {
3107 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3108 }
3109 }
3110 }
3111
3112 for (const audio_io_handle_t handle : inputsToClose) {
3113 ALOGV("%s closing input %d", __func__, handle);
3114 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003115 }
Eric Laurentd4692962014-05-05 18:13:44 -07003116}
3117
François Gaffie251c7f02018-11-07 10:41:08 +01003118void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003119{
3120 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003121 if (indexMin < 0 || indexMax < 0) {
3122 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3123 return;
3124 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003125 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003126
3127 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003128 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3129 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003130 continue;
3131 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003132 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003133 }
Eric Laurente552edb2014-03-10 17:42:56 -07003134}
3135
Eric Laurente0720872014-03-11 09:30:41 -07003136status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003137 int index,
3138 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003139{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003140 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003141 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3142 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3143 return NO_ERROR;
3144 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003145 ALOGV("%s: stream %s attributes=%s", __func__,
3146 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003147 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003148}
3149
Eric Laurente0720872014-03-11 09:30:41 -07003150status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003151 int *index,
3152 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003153{
François Gaffiec005e562018-11-06 15:04:49 +01003154 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3155 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003156 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003157 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003158 deviceTypes = mEngine->getOutputDevicesForStream(
3159 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003160 }
jiabin9a3361e2019-10-01 09:38:30 -07003161 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003162}
3163
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003164status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003165 int index,
3166 audio_devices_t device)
3167{
3168 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003169 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3170 if (group == VOLUME_GROUP_NONE) {
3171 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003172 return BAD_VALUE;
3173 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003174 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003175 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003176 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003177 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003178 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3179 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3180 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3181 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003182 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3183
3184 status = setVolumeCurveIndex(index, device, curves);
3185 if (status != NO_ERROR) {
3186 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3187 return status;
3188 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003189
jiabin9a3361e2019-10-01 09:38:30 -07003190 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003191 auto curCurvAttrs = curves.getAttributes();
3192 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3193 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003194 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003195 } else if (!curves.getStreamTypes().empty()) {
3196 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003197 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003198 } else {
3199 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3200 return BAD_VALUE;
3201 }
jiabin9a3361e2019-10-01 09:38:30 -07003202 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3203 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003204
François Gaffiecfe17322018-11-07 13:41:29 +01003205 // update volume on all outputs and streams matching the following:
3206 // - The requested stream (or a stream matching for volume control) is active on the output
3207 // - The device (or devices) selected by the engine for this stream includes
3208 // the requested device
3209 // - For non default requested device, currently selected device on the output is either the
3210 // requested device or one of the devices selected by the engine for this stream
3211 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3212 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003213 for (size_t i = 0; i < mOutputs.size(); i++) {
3214 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003215 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003216
jiabin9a3361e2019-10-01 09:38:30 -07003217 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3218 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003219 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003220
3221 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003222 continue;
3223 }
3224 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3225 curDevices.find(device) == curDevices.end()) {
3226 continue;
3227 }
3228 bool applyVolume = false;
3229 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3230 curSrcDevices.insert(device);
3231 applyVolume = (curSrcDevices.find(
3232 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3233 } else {
3234 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3235 }
3236 if (!applyVolume) {
3237 continue; // next output
3238 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003239 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3240 // If a higher priority strategy is active, and the output is routed to a device with a
3241 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003242 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003243 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003244 // If the volume source is active with higher priority source, ensure at least Sw Muted
3245 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003246 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3247 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3248 false /*preferredDevice*/);
3249 if (activeClients.empty()) {
3250 continue;
3251 }
3252 bool isPreempted = false;
3253 bool isHigherPriority = productStrategy < strategy;
3254 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003255 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003256 ALOGV("%s: Strategy=%d (\nrequester:\n"
3257 " group %d, volumeGroup=%d attributes=%s)\n"
3258 " higher priority source active:\n"
3259 " volumeGroup=%d attributes=%s) \n"
3260 " on output %zu, bailing out", __func__, productStrategy,
3261 group, group, toString(attributes).c_str(),
3262 client->volumeSource(), toString(client->attributes()).c_str(), i);
3263 applyVolume = false;
3264 isPreempted = true;
3265 break;
3266 }
3267 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003268 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003269 applyVolume = true;
3270 }
3271 }
3272 if (isPreempted || applyVolume) {
3273 break;
3274 }
3275 }
3276 if (!applyVolume) {
3277 continue; // next output
3278 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003279 }
François Gaffieed91f582020-01-31 10:35:37 +01003280 //FIXME: workaround for truncated touch sounds
3281 // delayed volume change for system stream to be removed when the problem is
3282 // handled by system UI
3283 status_t volStatus = checkAndSetVolume(
3284 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003285 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003286 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3287 if (volStatus != NO_ERROR) {
3288 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003289 }
3290 }
François Gaffiecfe17322018-11-07 13:41:29 +01003291 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3292 return status;
3293}
3294
François Gaffieaaac0fd2018-11-22 17:56:39 +01003295status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003296 audio_devices_t device,
3297 IVolumeCurves &volumeCurves)
3298{
3299 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3300 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003301 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3302 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003303 (index > volumeCurves.getVolumeIndexMax())) {
3304 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3305 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3306 return BAD_VALUE;
3307 }
3308 if (!audio_is_output_device(device)) {
3309 return BAD_VALUE;
3310 }
3311
3312 // Force max volume if stream cannot be muted
3313 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3314
François Gaffieaaac0fd2018-11-22 17:56:39 +01003315 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003316 volumeCurves.addCurrentVolumeIndex(device, index);
3317 return NO_ERROR;
3318}
3319
3320status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3321 int &index,
3322 audio_devices_t device)
3323{
3324 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3325 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003326 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003327 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003328 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003329 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003330 }
jiabin9a3361e2019-10-01 09:38:30 -07003331 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003332}
3333
3334status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3335 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003336 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003337{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003338 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003339 return BAD_VALUE;
3340 }
jiabin9a3361e2019-10-01 09:38:30 -07003341 index = curves.getVolumeIndex(deviceTypes);
3342 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003343 return NO_ERROR;
3344}
3345
3346status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3347 int &index)
3348{
3349 index = getVolumeCurves(attr).getVolumeIndexMin();
3350 return NO_ERROR;
3351}
3352
3353status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3354 int &index)
3355{
3356 index = getVolumeCurves(attr).getVolumeIndexMax();
3357 return NO_ERROR;
3358}
3359
Eric Laurent36829f92017-04-07 19:04:42 -07003360audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003361{
3362 // select one output among several suitable for global effects.
3363 // The priority is as follows:
3364 // 1: An offloaded output. If the effect ends up not being offloadable,
3365 // AudioFlinger will invalidate the track and the offloaded output
3366 // will be closed causing the effect to be moved to a PCM output.
3367 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003368 // 3: The primary output
3369 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003370
François Gaffiec005e562018-11-06 15:04:49 +01003371 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3372 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003373 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003374
Eric Laurent36829f92017-04-07 19:04:42 -07003375 if (outputs.size() == 0) {
3376 return AUDIO_IO_HANDLE_NONE;
3377 }
Eric Laurente552edb2014-03-10 17:42:56 -07003378
Eric Laurent36829f92017-04-07 19:04:42 -07003379 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3380 bool activeOnly = true;
3381
3382 while (output == AUDIO_IO_HANDLE_NONE) {
3383 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3384 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3385 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3386
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003387 for (audio_io_handle_t output : outputs) {
3388 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003389 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003390 continue;
3391 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003392 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3393 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003394 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003395 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003396 }
3397 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003398 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003399 }
3400 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003401 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003402 }
3403 }
3404 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3405 output = outputOffloaded;
3406 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3407 output = outputDeepBuffer;
3408 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3409 output = outputPrimary;
3410 } else {
3411 output = outputs[0];
3412 }
3413 activeOnly = false;
3414 }
3415
3416 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003417 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003418 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3419 mMusicEffectOutput = output;
3420 }
3421
3422 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003423 return output;
3424}
3425
Eric Laurent36829f92017-04-07 19:04:42 -07003426audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3427{
3428 return selectOutputForMusicEffects();
3429}
3430
Eric Laurente0720872014-03-11 09:30:41 -07003431status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003432 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003433 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003434 int session,
3435 int id)
3436{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003437 if (session != AUDIO_SESSION_DEVICE) {
3438 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003439 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003440 index = mInputs.indexOfKey(io);
3441 if (index < 0) {
3442 ALOGW("registerEffect() unknown io %d", io);
3443 return INVALID_OPERATION;
3444 }
Eric Laurente552edb2014-03-10 17:42:56 -07003445 }
3446 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003447 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3448 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3449 || strategy == PRODUCT_STRATEGY_NONE));
3450 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003451}
3452
Eric Laurentc241b0d2018-11-28 09:08:49 -08003453status_t AudioPolicyManager::unregisterEffect(int id)
3454{
3455 if (mEffects.getEffect(id) == nullptr) {
3456 return INVALID_OPERATION;
3457 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003458 if (mEffects.isEffectEnabled(id)) {
3459 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3460 setEffectEnabled(id, false);
3461 }
3462 return mEffects.unregisterEffect(id);
3463}
3464
3465status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3466{
3467 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3468 if (effect == nullptr) {
3469 return INVALID_OPERATION;
3470 }
3471
3472 status_t status = mEffects.setEffectEnabled(id, enabled);
3473 if (status == NO_ERROR) {
3474 mInputs.trackEffectEnabled(effect, enabled);
3475 }
3476 return status;
3477}
3478
Eric Laurent6c796322019-04-09 14:13:17 -07003479
3480status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3481{
3482 mEffects.moveEffects(ids, io);
3483 return NO_ERROR;
3484}
3485
Eric Laurentc75307b2015-03-17 15:29:32 -07003486bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3487{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003488 auto vs = toVolumeSource(stream, false);
3489 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003490}
3491
3492bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3493{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003494 auto vs = toVolumeSource(stream, false);
3495 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003496}
3497
Eric Laurente0720872014-03-11 09:30:41 -07003498bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003499{
3500 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003501 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003502 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003503 return true;
3504 }
3505 }
3506 return false;
3507}
3508
Eric Laurent275e8e92014-11-30 15:14:47 -08003509// Register a list of custom mixes with their attributes and format.
3510// When a mix is registered, corresponding input and output profiles are
3511// added to the remote submix hw module. The profile contains only the
3512// parameters (sampling rate, format...) specified by the mix.
3513// The corresponding input remote submix device is also connected.
3514//
3515// When a remote submix device is connected, the address is checked to select the
3516// appropriate profile and the corresponding input or output stream is opened.
3517//
3518// When capture starts, getInputForAttr() will:
3519// - 1 look for a mix matching the address passed in attribtutes tags if any
3520// - 2 if none found, getDeviceForInputSource() will:
3521// - 2.1 look for a mix matching the attributes source
3522// - 2.2 if none found, default to device selection by policy rules
3523// At this time, the corresponding output remote submix device is also connected
3524// and active playback use cases can be transferred to this mix if needed when reconnecting
3525// after AudioTracks are invalidated
3526//
3527// When playback starts, getOutputForAttr() will:
3528// - 1 look for a mix matching the address passed in attribtutes tags if any
3529// - 2 if none found, look for a mix matching the attributes usage
3530// - 3 if none found, default to device and output selection by policy rules.
3531
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003532status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003533{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003534 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3535 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003536 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003537 sp<HwModule> rSubmixModule;
3538 // examine each mix's route type
3539 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003540 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003541 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3542 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3543 ALOGE("Unsupported Policy Mix %zu of %zu: "
3544 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3545 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003546 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003547 break;
3548 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003549 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3550 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003551 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003552 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3553 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003554 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003555 rSubmixModule = mHwModules.getModuleFromName(
3556 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3557 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003558 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003559 i);
3560 res = INVALID_OPERATION;
3561 break;
3562 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003563 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003564
Eric Laurent97ac8712018-07-27 18:59:02 -07003565 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003566 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003567 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003568 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003569 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3570 } else {
3571 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3572 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003573 }
François Gaffie036e1e92015-03-19 10:16:24 +01003574
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003575 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003576 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003577 res = INVALID_OPERATION;
3578 break;
3579 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003580 audio_config_t outputConfig = mix.mFormat;
3581 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003582 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3583 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003584 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3585 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003586 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003587 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003588 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003589 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003590
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003591 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003592 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3593 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3594 ALOGE("Failed to set remote submix device available, type %u, address %s",
3595 mix.mDeviceType, address.string());
3596 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003597 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003598 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3599 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003600 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003601 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003602 i, mixes.size(), type, address.string());
3603
3604 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3605 mix.mDeviceType, mix.mDeviceAddress,
3606 String8(), AUDIO_FORMAT_DEFAULT);
3607 if (device == nullptr) {
3608 res = INVALID_OPERATION;
3609 break;
3610 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003611
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003612 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003613 // First try to find an already opened output supporting the device
3614 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003615 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003616
Eric Laurentc529cf62020-04-17 18:19:10 -07003617 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003618 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003619 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3620 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003621 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003622 } else {
3623 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003624 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003625 }
3626 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003627 // If no output found, try to find a direct output profile supporting the device
3628 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3629 sp<HwModule> module = mHwModules[i];
3630 for (size_t j = 0;
3631 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3632 j++) {
3633 sp<IOProfile> profile = module->getOutputProfiles()[j];
3634 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3635 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3636 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3637 address.string());
3638 res = INVALID_OPERATION;
3639 } else {
3640 foundOutput = true;
3641 }
3642 }
3643 }
3644 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003645 if (res != NO_ERROR) {
3646 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003647 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003648 res = INVALID_OPERATION;
3649 break;
3650 } else if (!foundOutput) {
3651 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003652 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003653 res = INVALID_OPERATION;
3654 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003655 } else {
3656 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003657 }
Eric Laurentc722f302014-12-10 11:21:49 -08003658 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003659 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003660 if (res != NO_ERROR) {
3661 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003662 } else if (checkOutputs) {
3663 checkForDeviceAndOutputChanges();
3664 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003665 }
3666 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003667}
3668
3669status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3670{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003671 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003672 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003673 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003674 sp<HwModule> rSubmixModule;
3675 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003676 for (const auto& mix : mixes) {
3677 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003678
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003679 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003680 rSubmixModule = mHwModules.getModuleFromName(
3681 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3682 if (rSubmixModule == 0) {
3683 res = INVALID_OPERATION;
3684 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003685 }
3686 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003687
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003688 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003689
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003690 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003691 res = INVALID_OPERATION;
3692 continue;
3693 }
3694
Kevin Rocard04ed0462019-05-02 17:53:24 -07003695 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3696 if (getDeviceConnectionState(device, address.string()) ==
3697 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3698 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3699 address.string(), "remote-submix",
3700 AUDIO_FORMAT_DEFAULT);
3701 if (res != OK) {
3702 ALOGE("Error making RemoteSubmix device unavailable for mix "
3703 "with type %d, address %s", device, address.string());
3704 }
3705 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003706 }
jiabin5740f082019-08-19 15:08:30 -07003707 rSubmixModule->removeOutputProfile(address.c_str());
3708 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003709
Kevin Rocard153f92d2018-12-18 18:33:28 -08003710 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003711 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003712 res = INVALID_OPERATION;
3713 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003714 } else {
3715 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003716 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003717 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003718 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003719 if (res == NO_ERROR && checkOutputs) {
3720 checkForDeviceAndOutputChanges();
3721 updateCallAndOutputRouting();
3722 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003723 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003724}
3725
Mikhail Naganov100f0122018-11-29 11:22:16 -08003726void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3727{
3728 size_t i = 0;
3729 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3730 for (const auto& fmt : mManualSurroundFormats) {
3731 if (i++ != 0) dst->append(", ");
3732 std::string sfmt;
3733 FormatConverter::toString(fmt, sfmt);
3734 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3735 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3736 }
3737}
3738
Eric Laurentc529cf62020-04-17 18:19:10 -07003739// Returns true if all devices types match the predicate and are supported by one HW module
3740bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003741 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003742 std::function<bool(audio_devices_t)> predicate,
3743 const char *context) {
3744 for (size_t i = 0; i < devices.size(); i++) {
3745 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003746 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003747 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003748 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003749 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003750 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003751 return false;
3752 }
3753 }
3754 return true;
3755}
3756
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003757status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003758 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003759 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003760 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3761 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003762 }
3763 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003764 if (res != NO_ERROR) {
3765 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3766 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003767 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003768
3769 checkForDeviceAndOutputChanges();
3770 updateCallAndOutputRouting();
3771
3772 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003773}
3774
3775status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3776 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003777 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3778 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003779 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003780 __FUNCTION__, uid);
3781 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003782 }
3783
Eric Laurentc529cf62020-04-17 18:19:10 -07003784 checkForDeviceAndOutputChanges();
3785 updateCallAndOutputRouting();
3786
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003787 return res;
3788}
3789
Eric Laurent2517af32020-11-25 15:31:27 +01003790
jiabin0a488932020-08-07 17:32:40 -07003791status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3792 device_role_t role,
3793 const AudioDeviceTypeAddrVector &devices) {
3794 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3795 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003796
Eric Laurentc529cf62020-04-17 18:19:10 -07003797 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003798 return BAD_VALUE;
3799 }
jiabin0a488932020-08-07 17:32:40 -07003800 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003801 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003802 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3803 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003804 return status;
3805 }
3806
3807 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003808
3809 bool forceVolumeReeval = false;
3810 // FIXME: workaround for truncated touch sounds
3811 // to be removed when the problem is handled by system UI
3812 uint32_t delayMs = 0;
3813 if (strategy == mCommunnicationStrategy) {
3814 forceVolumeReeval = true;
3815 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3816 updateInputRouting();
3817 }
3818 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003819
3820 return NO_ERROR;
3821}
3822
3823void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3824{
3825 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003826 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003827 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003828 // Only apply special touch sound delay once
3829 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003830 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003831 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003832 for (size_t i = 0; i < mOutputs.size(); i++) {
3833 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3834 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003835 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3836 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003837 // As done in setDeviceConnectionState, we could also fix default device issue by
3838 // preventing the force re-routing in case of default dev that distinguishes on address.
3839 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003840 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003841 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3842 // If the device is using preferred mixer attributes, the output need to reopen
3843 // with default configuration when the new selected devices are different from
3844 // current routing devices.
3845 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3846 continue;
3847 }
Francois Gaffie601801d2021-06-22 13:27:39 +02003848 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3849 true /*requiresMuteCheck*/,
3850 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003851 // Only apply special touch sound delay once
3852 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003853 }
3854 if (forceVolumeReeval && !newDevices.isEmpty()) {
3855 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3856 }
3857 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003858 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01003859 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003860}
3861
Eric Laurent2517af32020-11-25 15:31:27 +01003862void AudioPolicyManager::updateInputRouting() {
3863 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303864 // Skip for hotword recording as the input device switch
3865 // is handled within sound trigger HAL
3866 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3867 continue;
3868 }
Eric Laurent2517af32020-11-25 15:31:27 +01003869 auto newDevice = getNewInputDevice(activeDesc);
3870 // Force new input selection if the new device can not be reached via current input
3871 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3872 setInputDevice(activeDesc->mIoHandle, newDevice);
3873 } else {
3874 closeInput(activeDesc->mIoHandle);
3875 }
3876 }
3877}
3878
Paul Wang5d7cdb52022-11-22 09:45:06 +00003879status_t
3880AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3881 device_role_t role,
3882 const AudioDeviceTypeAddrVector &devices) {
3883 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3884 dumpAudioDeviceTypeAddrVector(devices).c_str());
3885
3886 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3887 return BAD_VALUE;
3888 }
3889 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
3890 if (status != NO_ERROR) {
3891 ALOGW("Engine could not remove devices %s for strategy %d role %d",
3892 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
3893 return status;
3894 }
3895
3896 checkForDeviceAndOutputChanges();
3897
3898 bool forceVolumeReeval = false;
3899 // TODO(b/263479999): workaround for truncated touch sounds
3900 // to be removed when the problem is handled by system UI
3901 uint32_t delayMs = 0;
3902 if (strategy == mCommunnicationStrategy) {
3903 forceVolumeReeval = true;
3904 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3905 updateInputRouting();
3906 }
3907 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
3908
3909 return NO_ERROR;
3910}
3911
3912status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
3913 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003914{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003915 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003916
Paul Wang5d7cdb52022-11-22 09:45:06 +00003917 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003918 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01003919 ALOGW_IF(status != NAME_NOT_FOUND,
3920 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01003921 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003922 return status;
3923 }
3924
3925 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003926
3927 bool forceVolumeReeval = false;
3928 // FIXME: workaround for truncated touch sounds
3929 // to be removed when the problem is handled by system UI
3930 uint32_t delayMs = 0;
3931 if (strategy == mCommunnicationStrategy) {
3932 forceVolumeReeval = true;
3933 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3934 updateInputRouting();
3935 }
3936 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003937
3938 return NO_ERROR;
3939}
3940
jiabin0a488932020-08-07 17:32:40 -07003941status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3942 device_role_t role,
3943 AudioDeviceTypeAddrVector &devices) {
3944 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003945}
3946
Jiabin Huang3b98d322020-09-03 17:54:16 +00003947status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3948 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3949 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3950 dumpAudioDeviceTypeAddrVector(devices).c_str());
3951
Mikhail Naganov55773032020-10-01 15:08:13 -07003952 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003953 return BAD_VALUE;
3954 }
3955 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3956 ALOGW_IF(status != NO_ERROR,
3957 "Engine could not set preferred devices %s for audio source %d role %d",
3958 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3959
3960 return status;
3961}
3962
3963status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3964 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3965 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3966 dumpAudioDeviceTypeAddrVector(devices).c_str());
3967
Mikhail Naganov55773032020-10-01 15:08:13 -07003968 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003969 return BAD_VALUE;
3970 }
3971 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3972 ALOGW_IF(status != NO_ERROR,
3973 "Engine could not add preferred devices %s for audio source %d role %d",
3974 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3975
Eric Laurent2517af32020-11-25 15:31:27 +01003976 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003977 return status;
3978}
3979
3980status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3981 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3982{
3983 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3984 dumpAudioDeviceTypeAddrVector(devices).c_str());
3985
Mikhail Naganov55773032020-10-01 15:08:13 -07003986 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003987 return BAD_VALUE;
3988 }
3989
3990 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3991 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01003992 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00003993 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01003994 if (status == NO_ERROR) {
3995 updateInputRouting();
3996 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00003997 return status;
3998}
3999
4000status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4001 device_role_t role) {
4002 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4003
4004 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004005 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004006 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004007 if (status == NO_ERROR) {
4008 updateInputRouting();
4009 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004010 return status;
4011}
4012
4013status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4014 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4015 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4016}
4017
Oscar Azucena90e77632019-11-27 17:12:28 -08004018status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004019 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004020 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004021 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4022 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004023 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004024 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4025 if (status != NO_ERROR) {
4026 ALOGE("%s() could not set device affinity for userId %d",
4027 __FUNCTION__, userId);
4028 return status;
4029 }
4030
4031 // reevaluate outputs for all devices
4032 checkForDeviceAndOutputChanges();
4033 updateCallAndOutputRouting();
4034
4035 return NO_ERROR;
4036}
4037
4038status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004039 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08004040 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4041 if (status != NO_ERROR) {
4042 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4043 __FUNCTION__, userId);
4044 return status;
4045 }
4046
4047 // reevaluate outputs for all devices
4048 checkForDeviceAndOutputChanges();
4049 updateCallAndOutputRouting();
4050
4051 return NO_ERROR;
4052}
4053
Andy Hungc29d82b2018-10-05 12:23:17 -07004054void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004055{
Andy Hungc29d82b2018-10-05 12:23:17 -07004056 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004057 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004058 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004059 std::string stateLiteral;
4060 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004061 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004062 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4063 "communications", "media", "record", "dock", "system",
4064 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4065 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4066 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004067 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4068 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4069 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4070 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4071 dst->append(" (MANUAL: ");
4072 dumpManualSurroundFormats(dst);
4073 dst->append(")");
4074 }
4075 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004076 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004077 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4078 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004079 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07004080 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01004081
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004082 dst->append("\n");
4083 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4084 dst->append("\n");
4085 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004086 mHwModulesAll.dump(dst);
4087 mOutputs.dump(dst);
4088 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004089 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004090 mAudioPatches.dump(dst);
4091 mPolicyMixes.dump(dst);
4092 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004093
Kevin Rocardb99cc752019-03-21 20:52:24 -07004094 dst->appendFormat(" AllowedCapturePolicies:\n");
4095 for (auto& policy : mAllowedCapturePolicies) {
4096 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4097 }
4098
jiabina84c3d32022-12-02 18:59:55 +00004099 dst->appendFormat(" Preferred mixer audio configuration:\n");
4100 for (const auto it : mPreferredMixerAttrInfos) {
4101 dst->appendFormat(" - device port id: %d\n", it.first);
4102 for (const auto preferredMixerInfoIt : it.second) {
4103 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4104 preferredMixerInfoIt.second->dump(dst);
4105 }
4106 }
4107
François Gaffiec005e562018-11-06 15:04:49 +01004108 dst->appendFormat("\nPolicy Engine dump:\n");
4109 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004110}
4111
4112status_t AudioPolicyManager::dump(int fd)
4113{
4114 String8 result;
4115 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07004116 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004117 return NO_ERROR;
4118}
4119
Kevin Rocardb99cc752019-03-21 20:52:24 -07004120status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4121{
4122 mAllowedCapturePolicies[uid] = capturePolicy;
4123 return NO_ERROR;
4124}
4125
Eric Laurente552edb2014-03-10 17:42:56 -07004126// This function checks for the parameters which can be offloaded.
4127// This can be enhanced depending on the capability of the DSP and policy
4128// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004129audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004130{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004131 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004132 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004133 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004134 offloadInfo.format,
4135 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4136 offloadInfo.has_video);
4137
jiabin2b9d5a12021-12-10 01:06:29 +00004138 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004139 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004140 }
4141
4142 // See if there is a profile to support this.
4143 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004144 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004145 offloadInfo.sample_rate,
4146 offloadInfo.format,
4147 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004148 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4149 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004150 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4151 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4152 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004153 if (profile == nullptr) {
4154 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4155 }
4156 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4157 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4158 }
4159 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004160}
4161
Michael Chana94fbb22018-04-24 14:31:19 +10004162bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4163 const audio_attributes_t& attributes) {
4164 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004165 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004166 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4167 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004168 config.sample_rate,
4169 config.format,
4170 config.channel_mask,
4171 output_flags,
4172 true /* directOnly */);
4173 ALOGV("%s() profile %sfound with name: %s, "
4174 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4175 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004176 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004177 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004178
4179 // also try the MSD module if compatible profile not found
4180 if (profile == nullptr) {
4181 profile = getMsdProfileForOutput(outputDevices,
4182 config.sample_rate,
4183 config.format,
4184 config.channel_mask,
4185 output_flags,
4186 true /* directOnly */);
4187 ALOGV("%s() MSD profile %sfound with name: %s, "
4188 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4189 __FUNCTION__, profile != 0 ? "" : "NOT ",
4190 (profile != 0 ? profile->getTagName().c_str() : "null"),
4191 config.sample_rate, config.format, config.channel_mask, output_flags);
4192 }
4193 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004194}
4195
jiabin2b9d5a12021-12-10 01:06:29 +00004196bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4197 bool durationIgnored) {
4198 if (mMasterMono) {
4199 return false; // no offloading if mono is set.
4200 }
4201
4202 // Check if offload has been disabled
4203 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4204 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4205 return false;
4206 }
4207
4208 // Check if stream type is music, then only allow offload as of now.
4209 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4210 {
4211 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4212 return false;
4213 }
4214
4215 //TODO: enable audio offloading with video when ready
4216 const bool allowOffloadWithVideo =
4217 property_get_bool("audio.offload.video", false /* default_value */);
4218 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4219 ALOGV("%s: has_video == true, returning false", __func__);
4220 return false;
4221 }
4222
4223 //If duration is less than minimum value defined in property, return false
4224 const int min_duration_secs = property_get_int32(
4225 "audio.offload.min.duration.secs", -1 /* default_value */);
4226 if (!durationIgnored) {
4227 if (min_duration_secs >= 0) {
4228 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4229 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4230 __func__, min_duration_secs);
4231 return false;
4232 }
4233 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4234 ALOGV("%s: Offload denied by duration < default min(=%u)",
4235 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4236 return false;
4237 }
4238 }
4239
4240 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4241 // creating an offloaded track and tearing it down immediately after start when audioflinger
4242 // detects there is an active non offloadable effect.
4243 // FIXME: We should check the audio session here but we do not have it in this context.
4244 // This may prevent offloading in rare situations where effects are left active by apps
4245 // in the background.
4246 if (mEffects.isNonOffloadableEffectEnabled()) {
4247 return false;
4248 }
4249
4250 return true;
4251}
4252
4253audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4254 const audio_config_t *config) {
4255 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4256 offloadInfo.format = config->format;
4257 offloadInfo.sample_rate = config->sample_rate;
4258 offloadInfo.channel_mask = config->channel_mask;
4259 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4260 offloadInfo.has_video = false;
4261 offloadInfo.is_streaming = false;
4262 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4263
4264 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4265 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4266 audio_flags_to_audio_output_flags(attr->flags, &flags);
4267 // only retain flags that will drive compressed offload or passthrough
4268 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4269 if (offloadPossible) {
4270 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4271 }
4272 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4273
Dorin Drimusfae3c642022-03-17 18:36:30 +01004274 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004275 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004276 DeviceVector outputDevices = engineOutputDevices;
4277 // the MSD module checks for different conditions and output devices
4278 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4279 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4280 continue;
4281 }
4282 outputDevices = getMsdAudioOutDevices();
4283 }
jiabin2b9d5a12021-12-10 01:06:29 +00004284 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004285 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004286 config->sample_rate, nullptr /*updatedSamplingRate*/,
4287 config->format, nullptr /*updatedFormat*/,
4288 config->channel_mask, nullptr /*updatedChannelMask*/,
4289 flags)) {
4290 continue;
4291 }
4292 // reject profiles not corresponding to a device currently available
4293 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4294 continue;
4295 }
4296 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4297 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004298 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004299 != AUDIO_DIRECT_NOT_SUPPORTED) {
4300 // Already reports offload gapless supported. No need to report offload support.
4301 continue;
4302 }
4303 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4304 != AUDIO_OUTPUT_FLAG_NONE) {
4305 // If offload gapless is reported, no need to report offload support.
4306 directMode = (audio_direct_mode_t) ((directMode &
4307 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4308 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4309 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004310 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004311 }
4312 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004313 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004314 }
4315 }
4316 }
4317 return directMode;
4318}
4319
Dorin Drimusf2196d82022-01-03 12:11:18 +01004320status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4321 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004322 if (mEffects.isNonOffloadableEffectEnabled()) {
4323 return OK;
4324 }
jiabinf1c73972022-04-14 16:28:52 -07004325 DeviceVector devices;
4326 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004327 if (status != OK) {
4328 return status;
4329 }
4330 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4331 if (devices.empty()) {
4332 return OK; // no output devices for the attributes
4333 }
jiabinf1c73972022-04-14 16:28:52 -07004334 return getProfilesForDevices(devices, audioProfilesVector,
4335 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004336}
4337
jiabina84c3d32022-12-02 18:59:55 +00004338status_t AudioPolicyManager::getSupportedMixerAttributes(
4339 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4340 ALOGV("%s, portId=%d", __func__, portId);
4341 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4342 if (deviceDescriptor == nullptr) {
4343 ALOGE("%s the requested device is currently unavailable", __func__);
4344 return BAD_VALUE;
4345 }
4346 for (const auto& hwModule : mHwModules) {
4347 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4348 if (curProfile->supportsDevice(deviceDescriptor)) {
4349 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4350 }
4351 }
4352 }
4353 return NO_ERROR;
4354}
4355
4356status_t AudioPolicyManager::setPreferredMixerAttributes(
4357 const audio_attributes_t *attr,
4358 audio_port_handle_t portId,
4359 uid_t uid,
4360 const audio_mixer_attributes_t *mixerAttributes) {
4361 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4362 "mixerBehavior=%d}, uid=%d, portId=%u",
4363 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4364 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4365 mixerAttributes->mixer_behavior, uid, portId);
4366 if (attr->usage != AUDIO_USAGE_MEDIA) {
4367 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4368 return BAD_VALUE;
4369 }
4370 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4371 if (deviceDescriptor == nullptr) {
4372 ALOGE("%s the requested device is currently unavailable", __func__);
4373 return BAD_VALUE;
4374 }
4375 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4376 ALOGE("%s(%d), type=%d, is not a usb output device",
4377 __func__, portId, deviceDescriptor->type());
4378 return BAD_VALUE;
4379 }
4380
4381 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4382 audio_flags_to_audio_output_flags(attr->flags, &flags);
4383 flags = (audio_output_flags_t) (flags |
4384 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4385 sp<IOProfile> profile = nullptr;
4386 DeviceVector devices(deviceDescriptor);
4387 for (const auto& hwModule : mHwModules) {
4388 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4389 if (curProfile->hasDynamicAudioProfile()
4390 && curProfile->isCompatibleProfile(devices,
4391 mixerAttributes->config.sample_rate,
4392 nullptr /*updatedSamplingRate*/,
4393 mixerAttributes->config.format,
4394 nullptr /*updatedFormat*/,
4395 mixerAttributes->config.channel_mask,
4396 nullptr /*updatedChannelMask*/,
4397 flags,
4398 false /*exactMatchRequiredForInputFlags*/)) {
4399 profile = curProfile;
4400 break;
4401 }
4402 }
4403 }
4404 if (profile == nullptr) {
4405 ALOGE("%s, there is no compatible profile found", __func__);
4406 return BAD_VALUE;
4407 }
4408
4409 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4410 sp<PreferredMixerAttributesInfo>::make(
4411 uid, portId, profile, flags, *mixerAttributes);
4412 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4413 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4414
4415 // If 1) there is any client from the preferred mixer configuration owner that is currently
4416 // active and matches the strategy and 2) current output is on the preferred device and the
4417 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4418 // configuration.
4419 std::vector<audio_io_handle_t> outputsToReopen;
4420 for (size_t i = 0; i < mOutputs.size(); i++) {
4421 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004422 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4423 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4424 output->mUsePreferredMixerAttributes = true;
4425 } else {
4426 for (const auto &client: output->getActiveClients()) {
4427 if (client->uid() == uid && client->strategy() == strategy) {
4428 client->setIsInvalid();
4429 outputsToReopen.push_back(output->mIoHandle);
4430 }
jiabina84c3d32022-12-02 18:59:55 +00004431 }
4432 }
4433 }
4434 }
4435 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4436 config.sample_rate = mixerAttributes->config.sample_rate;
4437 config.channel_mask = mixerAttributes->config.channel_mask;
4438 config.format = mixerAttributes->config.format;
4439 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004440 sp<SwAudioOutputDescriptor> desc =
4441 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4442 if (desc == nullptr) {
4443 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4444 continue;
4445 }
4446 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004447 }
4448
4449 return NO_ERROR;
4450}
4451
4452sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
4453 audio_port_handle_t devicePortId, product_strategy_t strategy) {
4454 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4455 if (it == mPreferredMixerAttrInfos.end()) {
4456 return nullptr;
4457 }
4458 auto mixerAttrInfoIt = it->second.find(strategy);
4459 if (mixerAttrInfoIt == it->second.end()) {
4460 return nullptr;
4461 }
4462 return mixerAttrInfoIt->second;
4463}
4464
4465status_t AudioPolicyManager::getPreferredMixerAttributes(
4466 const audio_attributes_t *attr,
4467 audio_port_handle_t portId,
4468 audio_mixer_attributes_t* mixerAttributes) {
4469 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4470 portId, mEngine->getProductStrategyForAttributes(*attr));
4471 if (info == nullptr) {
4472 return NAME_NOT_FOUND;
4473 }
4474 *mixerAttributes = info->getMixerAttributes();
4475 return NO_ERROR;
4476}
4477
4478status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4479 audio_port_handle_t portId,
4480 uid_t uid) {
4481 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4482 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4483 if (preferredMixerAttrInfo == nullptr) {
4484 return NAME_NOT_FOUND;
4485 }
4486 if (preferredMixerAttrInfo->getUid() != uid) {
4487 ALOGE("%s, requested uid=%d, owned uid=%d",
4488 __func__, uid, preferredMixerAttrInfo->getUid());
4489 return PERMISSION_DENIED;
4490 }
4491 mPreferredMixerAttrInfos[portId].erase(strategy);
4492 if (mPreferredMixerAttrInfos[portId].empty()) {
4493 mPreferredMixerAttrInfos.erase(portId);
4494 }
4495
4496 // Reconfig existing output
4497 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4498 for (size_t i = 0; i < mOutputs.size(); i++) {
4499 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4500 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4501 }
4502 }
4503 for (const auto output : potentialOutputsToReopen) {
4504 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4505 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4506 preferredMixerAttrInfo->getFlags())) {
4507 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4508 }
4509 }
4510 return NO_ERROR;
4511}
4512
Eric Laurent6a94d692014-05-20 11:18:06 -07004513status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4514 audio_port_type_t type,
4515 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004516 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004517 unsigned int *generation)
4518{
jiabin19cdba52020-11-24 11:28:58 -08004519 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4520 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004521 return BAD_VALUE;
4522 }
4523 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004524 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004525 *num_ports = 0;
4526 }
4527
4528 size_t portsWritten = 0;
4529 size_t portsMax = *num_ports;
4530 *num_ports = 0;
4531 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004532 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4533 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004534 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004535 for (const auto& dev : mAvailableOutputDevices) {
4536 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004537 continue;
4538 }
4539 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004540 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004541 }
4542 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004543 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004544 }
4545 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004546 for (const auto& dev : mAvailableInputDevices) {
4547 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004548 continue;
4549 }
4550 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004551 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004552 }
4553 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004554 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004555 }
4556 }
4557 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4558 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4559 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4560 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4561 }
4562 *num_ports += mInputs.size();
4563 }
4564 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004565 size_t numOutputs = 0;
4566 for (size_t i = 0; i < mOutputs.size(); i++) {
4567 if (!mOutputs[i]->isDuplicated()) {
4568 numOutputs++;
4569 if (portsWritten < portsMax) {
4570 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4571 }
4572 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004573 }
Eric Laurent84c70242014-06-23 08:46:27 -07004574 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004575 }
4576 }
jiabina84c3d32022-12-02 18:59:55 +00004577
Eric Laurent6a94d692014-05-20 11:18:06 -07004578 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004579 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004580 return NO_ERROR;
4581}
4582
jiabin19cdba52020-11-24 11:28:58 -08004583status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004584{
Eric Laurent99fcae42018-05-17 16:59:18 -07004585 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4586 return BAD_VALUE;
4587 }
4588 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4589 if (dev != 0) {
4590 dev->toAudioPort(port);
4591 return NO_ERROR;
4592 }
4593 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4594 if (dev != 0) {
4595 dev->toAudioPort(port);
4596 return NO_ERROR;
4597 }
4598 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4599 if (out != 0) {
4600 out->toAudioPort(port);
4601 return NO_ERROR;
4602 }
4603 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4604 if (in != 0) {
4605 in->toAudioPort(port);
4606 return NO_ERROR;
4607 }
4608 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004609}
4610
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004611status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4612 audio_patch_handle_t *handle,
4613 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004614{
François Gaffieafd4cea2019-11-18 15:50:22 +01004615 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004616 if (handle == NULL || patch == NULL) {
4617 return BAD_VALUE;
4618 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004619 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004620 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004621 return BAD_VALUE;
4622 }
4623 // only one source per audio patch supported for now
4624 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004625 return INVALID_OPERATION;
4626 }
Eric Laurent874c42872014-08-08 15:13:39 -07004627 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004628 return INVALID_OPERATION;
4629 }
Eric Laurent874c42872014-08-08 15:13:39 -07004630 for (size_t i = 0; i < patch->num_sinks; i++) {
4631 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4632 return INVALID_OPERATION;
4633 }
4634 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004635
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004636 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4637 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4638 if (srcDevice == nullptr || sinkDevice == nullptr) {
4639 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4640 return BAD_VALUE;
4641 }
4642 ALOGV("%s between source %s and sink %s", __func__,
4643 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4644 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4645 // Default attributes, default volume priority, not to infer with non raw audio patches.
4646 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4647 const struct audio_port_config *source = &patch->sources[0];
4648 sp<SourceClientDescriptor> sourceDesc =
4649 new InternalSourceClientDescriptor(
4650 portId, uid, attributes, *source, srcDevice, sinkDevice,
4651 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4652
4653 status_t status =
4654 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4655
4656 if (status != NO_ERROR) {
4657 return INVALID_OPERATION;
4658 }
4659 mAudioSources.add(portId, sourceDesc);
4660 return NO_ERROR;
4661}
4662
4663status_t AudioPolicyManager::connectAudioSourceToSink(
4664 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4665 const struct audio_patch *patch,
4666 audio_patch_handle_t &handle,
4667 uid_t uid, uint32_t delayMs)
4668{
4669 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4670 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4671 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4672 return INVALID_OPERATION;
4673 }
4674 sourceDesc->connect(handle, sinkDevice);
4675 if (isMsdPatch(handle)) {
4676 return NO_ERROR;
4677 }
4678 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4679 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4680 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4681 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4682 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4683 goto FailurePatchAdded;
4684 }
4685 status = swOutput->start();
4686 if (status != NO_ERROR) {
4687 goto FailureSourceAdded;
4688 }
4689 swOutput->addClient(sourceDesc);
4690 status = startSource(swOutput, sourceDesc, &delayMs);
4691 if (status != NO_ERROR) {
4692 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4693 goto FailureSourceActive;
4694 }
4695 if (delayMs != 0) {
4696 usleep(delayMs * 1000);
4697 }
4698 return NO_ERROR;
4699
4700FailureSourceActive:
4701 swOutput->stop();
4702 releaseOutput(sourceDesc->portId());
4703FailureSourceAdded:
4704 sourceDesc->setSwOutput(nullptr);
4705FailurePatchAdded:
4706 releaseAudioPatchInternal(handle);
4707 return INVALID_OPERATION;
4708}
4709
4710status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4711 audio_patch_handle_t *handle,
4712 uid_t uid, uint32_t delayMs,
4713 const sp<SourceClientDescriptor>& sourceDesc)
4714{
4715 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004716 sp<AudioPatch> patchDesc;
4717 ssize_t index = mAudioPatches.indexOfKey(*handle);
4718
François Gaffieafd4cea2019-11-18 15:50:22 +01004719 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4720 patch->sources[0].role,
4721 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004722#if LOG_NDEBUG == 0
4723 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004724 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4725 patch->sinks[i].role,
4726 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004727 }
4728#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004729
4730 if (index >= 0) {
4731 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004732 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4733 __func__, mUidCached, patchDesc->getUid(), uid);
4734 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004735 return INVALID_OPERATION;
4736 }
4737 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004738 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004739 }
4740
4741 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004742 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004743 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004744 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004745 return BAD_VALUE;
4746 }
Eric Laurent84c70242014-06-23 08:46:27 -07004747 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4748 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004749 if (patchDesc != 0) {
4750 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004751 ALOGV("%s source id differs for patch current id %d new id %d",
4752 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004753 return BAD_VALUE;
4754 }
4755 }
Eric Laurent874c42872014-08-08 15:13:39 -07004756 DeviceVector devices;
4757 for (size_t i = 0; i < patch->num_sinks; i++) {
4758 // Only support mix to devices connection
4759 // TODO add support for mix to mix connection
4760 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004761 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004762 return INVALID_OPERATION;
4763 }
4764 sp<DeviceDescriptor> devDesc =
4765 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4766 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004767 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004768 return BAD_VALUE;
4769 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004770
François Gaffie11d30102018-11-02 16:09:09 +01004771 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004772 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004773 NULL, // updatedSamplingRate
4774 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004775 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004776 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004777 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004778 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004779 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004780 return INVALID_OPERATION;
4781 }
4782 devices.add(devDesc);
4783 }
4784 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004785 return INVALID_OPERATION;
4786 }
Eric Laurent874c42872014-08-08 15:13:39 -07004787
Eric Laurent6a94d692014-05-20 11:18:06 -07004788 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004789 ALOGV("%s setting device %s on output %d",
4790 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004791 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004792 index = mAudioPatches.indexOfKey(*handle);
4793 if (index >= 0) {
4794 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004795 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004796 }
4797 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004798 patchDesc->setUid(uid);
4799 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004800 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004801 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004802 return INVALID_OPERATION;
4803 }
4804 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4805 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4806 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004807 // only one sink supported when connecting an input device to a mix
4808 if (patch->num_sinks > 1) {
4809 return INVALID_OPERATION;
4810 }
François Gaffie53615e22015-03-19 09:24:12 +01004811 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004812 if (inputDesc == NULL) {
4813 return BAD_VALUE;
4814 }
4815 if (patchDesc != 0) {
4816 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4817 return BAD_VALUE;
4818 }
4819 }
François Gaffie11d30102018-11-02 16:09:09 +01004820 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004821 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004822 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004823 return BAD_VALUE;
4824 }
4825
François Gaffie11d30102018-11-02 16:09:09 +01004826 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004827 patch->sinks[0].sample_rate,
4828 NULL, /*updatedSampleRate*/
4829 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004830 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004831 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004832 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004833 // FIXME for the parameter type,
4834 // and the NONE
4835 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004836 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004837 return INVALID_OPERATION;
4838 }
4839 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004840 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004841 device->toString().c_str(), inputDesc->mIoHandle);
4842 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004843 index = mAudioPatches.indexOfKey(*handle);
4844 if (index >= 0) {
4845 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004846 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004847 }
4848 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004849 patchDesc->setUid(uid);
4850 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004851 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004852 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004853 return INVALID_OPERATION;
4854 }
4855 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4856 // device to device connection
4857 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004858 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004859 return BAD_VALUE;
4860 }
4861 }
François Gaffie11d30102018-11-02 16:09:09 +01004862 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004863 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004864 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004865 return BAD_VALUE;
4866 }
Eric Laurent874c42872014-08-08 15:13:39 -07004867
Eric Laurent6a94d692014-05-20 11:18:06 -07004868 //update source and sink with our own data as the data passed in the patch may
4869 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004870 PatchBuilder patchBuilder;
4871 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004872
4873 // if first sink is to MSD, establish single MSD patch
4874 if (getMsdAudioOutDevices().contains(
4875 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4876 ALOGV("%s patching to MSD", __FUNCTION__);
4877 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4878 goto installPatch;
4879 }
4880
François Gaffieafd4cea2019-11-18 15:50:22 +01004881 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4882 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004883
Eric Laurent874c42872014-08-08 15:13:39 -07004884 for (size_t i = 0; i < patch->num_sinks; i++) {
4885 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004886 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004887 return INVALID_OPERATION;
4888 }
François Gaffie11d30102018-11-02 16:09:09 +01004889 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004890 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004891 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004892 return BAD_VALUE;
4893 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004894 audio_port_config sinkPortConfig = {};
4895 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4896 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004897
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004898 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4899 // volume management purpose (tracking activity)
4900 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4901 // in config XML to reach the sink so that is can be declared as available.
4902 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004903 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004904 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004905 // take care of dynamic routing for SwOutput selection,
4906 audio_attributes_t attributes = sourceDesc->attributes();
4907 audio_stream_type_t stream = sourceDesc->stream();
4908 audio_attributes_t resultAttr;
4909 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4910 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02004911 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
4912 config.channel_mask =
4913 (audio_channel_mask_get_representation(sourceMask)
4914 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
4915 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004916 config.format = sourceDesc->config().format;
4917 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4918 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4919 bool isRequestedDeviceForExclusiveUse = false;
4920 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004921 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00004922 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004923 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4924 &stream, sourceDesc->uid(), &config, &flags,
4925 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00004926 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004927 if (output == AUDIO_IO_HANDLE_NONE) {
4928 ALOGV("%s no output for device %s",
4929 __FUNCTION__, sinkDevice->toString().c_str());
4930 return INVALID_OPERATION;
4931 }
4932 outputDesc = mOutputs.valueFor(output);
4933 if (outputDesc->isDuplicated()) {
4934 ALOGE("%s output is duplicated", __func__);
4935 return INVALID_OPERATION;
4936 }
François Gaffie7e39df22022-04-26 12:48:49 +02004937 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4938 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004939 } else {
4940 // Same for "raw patches" aka created from createAudioPatch API
4941 SortedVector<audio_io_handle_t> outputs =
4942 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4943 // if the sink device is reachable via an opened output stream, request to
4944 // go via this output stream by adding a second source to the patch
4945 // description
4946 output = selectOutput(outputs);
4947 if (output == AUDIO_IO_HANDLE_NONE) {
4948 ALOGE("%s no output available for internal patch sink", __func__);
4949 return INVALID_OPERATION;
4950 }
4951 outputDesc = mOutputs.valueFor(output);
4952 if (outputDesc->isDuplicated()) {
4953 ALOGV("%s output for device %s is duplicated",
4954 __func__, sinkDevice->toString().c_str());
4955 return INVALID_OPERATION;
4956 }
François Gaffie7e39df22022-04-26 12:48:49 +02004957 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004958 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004959 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004960 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004961 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004962 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004963 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4964 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004965 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4966 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004967 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004968 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004969 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004970 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004971 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004972 return INVALID_OPERATION;
4973 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004974 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004975 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004976 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004977 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004978 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02004979 srcMixPortConfig.ext.mix.usecase.stream =
4980 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004981 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4982 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004983 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004984 }
Eric Laurent83b88082014-06-20 18:31:16 -07004985 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004986 }
4987 // TODO: check from routing capabilities in config file and other conflicting patches
4988
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004989installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004990 status_t status = installPatch(
4991 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004992 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004993 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004994 return INVALID_OPERATION;
4995 }
4996 } else {
4997 return BAD_VALUE;
4998 }
4999 } else {
5000 return BAD_VALUE;
5001 }
5002 return NO_ERROR;
5003}
5004
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005005status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005006{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005007 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005008 ssize_t index = mAudioPatches.indexOfKey(handle);
5009
5010 if (index < 0) {
5011 return BAD_VALUE;
5012 }
5013 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005014 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5015 __func__, mUidCached, patchDesc->getUid(), uid);
5016 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005017 return INVALID_OPERATION;
5018 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005019 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5020 for (size_t i = 0; i < mAudioSources.size(); i++) {
5021 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5022 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5023 portId = sourceDesc->portId();
5024 break;
5025 }
5026 }
5027 return portId != AUDIO_PORT_HANDLE_NONE ?
5028 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005029}
Eric Laurent6a94d692014-05-20 11:18:06 -07005030
François Gaffieafd4cea2019-11-18 15:50:22 +01005031status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005032 uint32_t delayMs,
5033 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005034{
5035 ALOGV("%s patch %d", __func__, handle);
5036 if (mAudioPatches.indexOfKey(handle) < 0) {
5037 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5038 return BAD_VALUE;
5039 }
5040 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005041 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005042 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005043 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005044 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005045 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005046 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005047 return BAD_VALUE;
5048 }
5049
François Gaffie11d30102018-11-02 16:09:09 +01005050 setOutputDevices(outputDesc,
5051 getNewOutputDevices(outputDesc, true /*fromCache*/),
5052 true,
5053 0,
5054 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005055 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5056 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005057 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005058 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005059 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005060 return BAD_VALUE;
5061 }
5062 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005063 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005064 true,
5065 NULL);
5066 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005067 status_t status =
5068 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5069 ALOGV("%s patch panel returned %d patchHandle %d",
5070 __func__, status, patchDesc->getAfHandle());
5071 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005072 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005073 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005074 // SW or HW Bridge
5075 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5076 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005077 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005078 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5079 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5080 outputDesc = sourceDesc->swOutput().promote();
5081 }
5082 if (outputDesc == nullptr) {
5083 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5084 // releaseOutput has already called closeOutput in case of direct output
5085 return NO_ERROR;
5086 }
François Gaffie7e39df22022-04-26 12:48:49 +02005087 patchHandle = outputDesc->getPatchHandle();
5088 // When a Sw bridge is released, the mixer used by this bridge will release its
5089 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
5090 // Reuse patch handle to force audio flinger removing initial mixer patch removal
5091 // updating hal patch handle (prevent leaks).
5092 // While using a HwBridge, force reconsidering device only if not reusing an existing
5093 // output and no more activity on output (will force to close).
5094 bool force = sourceDesc->useSwBridge() ||
5095 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
5096 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5097 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5098 // Reconsider device only for cases:
5099 // 1 / Active Output
5100 // 2 / Inactive Output previously hosting HwBridge
5101 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5102 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5103 sourceDesc->canCloseOutput();
5104 setOutputDevices(outputDesc,
5105 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5106 outputDesc->devices(),
5107 force,
5108 0,
5109 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005110 } else {
5111 return BAD_VALUE;
5112 }
5113 } else {
5114 return BAD_VALUE;
5115 }
5116 return NO_ERROR;
5117}
5118
5119status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5120 struct audio_patch *patches,
5121 unsigned int *generation)
5122{
François Gaffie53615e22015-03-19 09:24:12 +01005123 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005124 return BAD_VALUE;
5125 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005126 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005127 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005128}
5129
Eric Laurente1715a42014-05-20 11:30:42 -07005130status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005131{
Eric Laurente1715a42014-05-20 11:30:42 -07005132 ALOGV("setAudioPortConfig()");
5133
5134 if (config == NULL) {
5135 return BAD_VALUE;
5136 }
5137 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5138 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005139 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5140 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005141 }
5142
Eric Laurenta121f902014-06-03 13:32:54 -07005143 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005144 if (config->type == AUDIO_PORT_TYPE_MIX) {
5145 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005146 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005147 if (outputDesc == NULL) {
5148 return BAD_VALUE;
5149 }
Eric Laurent84c70242014-06-23 08:46:27 -07005150 ALOG_ASSERT(!outputDesc->isDuplicated(),
5151 "setAudioPortConfig() called on duplicated output %d",
5152 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005153 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005154 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005155 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005156 if (inputDesc == NULL) {
5157 return BAD_VALUE;
5158 }
Eric Laurenta121f902014-06-03 13:32:54 -07005159 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005160 } else {
5161 return BAD_VALUE;
5162 }
5163 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5164 sp<DeviceDescriptor> deviceDesc;
5165 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5166 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5167 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5168 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5169 } else {
5170 return BAD_VALUE;
5171 }
5172 if (deviceDesc == NULL) {
5173 return BAD_VALUE;
5174 }
Eric Laurenta121f902014-06-03 13:32:54 -07005175 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005176 } else {
5177 return BAD_VALUE;
5178 }
5179
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005180 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005181 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5182 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005183 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005184 audioPortConfig->toAudioPortConfig(&newConfig, config);
5185 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005186 }
Eric Laurenta121f902014-06-03 13:32:54 -07005187 if (status != NO_ERROR) {
5188 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005189 }
Eric Laurente1715a42014-05-20 11:30:42 -07005190
5191 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005192}
5193
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005194void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5195{
Eric Laurentd60560a2015-04-10 11:31:20 -07005196 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005197 clearAudioPatches(uid);
5198 clearSessionRoutes(uid);
5199}
5200
Eric Laurent6a94d692014-05-20 11:18:06 -07005201void AudioPolicyManager::clearAudioPatches(uid_t uid)
5202{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005203 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005204 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005205 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005206 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005207 }
5208 }
5209}
5210
François Gaffiec005e562018-11-06 15:04:49 +01005211void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005212{
François Gaffiec005e562018-11-06 15:04:49 +01005213 // Take the first attributes following the product strategy as it is used to retrieve the routed
5214 // device. All attributes wihin a strategy follows the same "routing strategy"
5215 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5216 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005217 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005218 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005219 for (size_t j = 0; j < mOutputs.size(); j++) {
5220 if (mOutputs.keyAt(j) == ouptutToSkip) {
5221 continue;
5222 }
5223 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005224 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005225 continue;
5226 }
5227 // If the default device for this strategy is on another output mix,
5228 // invalidate all tracks in this strategy to force re connection.
5229 // Otherwise select new device on the output mix.
5230 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005231 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005232 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005233 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5234 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5235 // If the device is using preferred mixer attributes, the output need to reopen
5236 // with default configuration when the new selected devices are different from
5237 // current routing devices.
5238 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5239 continue;
5240 }
5241 setOutputDevices(outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005242 }
5243 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005244 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005245}
5246
5247void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5248{
5249 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005250 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005251 for (size_t i = 0; i < mOutputs.size(); i++) {
5252 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005253 for (const auto& client : outputDesc->getClientIterable()) {
5254 if (client->hasPreferredDevice() && client->uid() == uid) {
5255 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005256 auto clientStrategy = client->strategy();
5257 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5258 end(affectedStrategies)) {
5259 continue;
5260 }
5261 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005262 }
5263 }
5264 }
5265 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005266 for (const auto& strategy : affectedStrategies) {
5267 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005268 }
5269
5270 // remove input routes associated with this uid
5271 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005272 for (size_t i = 0; i < mInputs.size(); i++) {
5273 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005274 for (const auto& client : inputDesc->getClientIterable()) {
5275 if (client->hasPreferredDevice() && client->uid() == uid) {
5276 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5277 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005278 }
5279 }
5280 }
5281 // reroute inputs if necessary
5282 SortedVector<audio_io_handle_t> inputsToClose;
5283 for (size_t i = 0; i < mInputs.size(); i++) {
5284 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005285 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005286 inputsToClose.add(inputDesc->mIoHandle);
5287 }
5288 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005289 for (const auto& input : inputsToClose) {
5290 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005291 }
5292}
5293
Eric Laurentd60560a2015-04-10 11:31:20 -07005294void AudioPolicyManager::clearAudioSources(uid_t uid)
5295{
5296 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005297 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5298 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005299 stopAudioSource(mAudioSources.keyAt(i));
5300 }
5301 }
5302}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005303
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005304status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5305 audio_io_handle_t *ioHandle,
5306 audio_devices_t *device)
5307{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005308 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5309 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005310 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01005311 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005312
François Gaffiedf372692015-03-19 10:43:27 +01005313 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005314}
5315
Eric Laurentd60560a2015-04-10 11:31:20 -07005316status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005317 const audio_attributes_t *attributes,
5318 audio_port_handle_t *portId,
5319 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005320{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005321 ALOGV("%s", __FUNCTION__);
5322 *portId = AUDIO_PORT_HANDLE_NONE;
5323
5324 if (source == NULL || attributes == NULL || portId == NULL) {
5325 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5326 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005327 return BAD_VALUE;
5328 }
5329
Eric Laurentd60560a2015-04-10 11:31:20 -07005330 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5331 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005332 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5333 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005334 return INVALID_OPERATION;
5335 }
5336
François Gaffie11d30102018-11-02 16:09:09 +01005337 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005338 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005339 String8(source->ext.device.address),
5340 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005341 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005342 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005343 return BAD_VALUE;
5344 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005345
jiabin4ef93452019-09-10 14:29:54 -07005346 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005347
François Gaffieaaac0fd2018-11-22 17:56:39 +01005348 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005349 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005350 mEngine->getStreamTypeForAttributes(*attributes),
5351 mEngine->getProductStrategyForAttributes(*attributes),
5352 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005353
5354 status_t status = connectAudioSource(sourceDesc);
5355 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005356 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005357 }
5358 return status;
5359}
5360
Francois Gaffie601801d2021-06-22 13:27:39 +02005361sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5362 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5363{
5364 ALOGV("%s", __FUNCTION__);
5365 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5366
5367 status_t status = startAudioSource(source, attributes, &portId, uid);
5368 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5369 return mAudioSources.valueFor(portId);
5370}
5371
5372
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005373status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005374{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005375 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005376
5377 // make sure we only have one patch per source.
5378 disconnectAudioSource(sourceDesc);
5379
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005380 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005381 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5382 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5383 sourceDesc->srcDevice()->type(),
5384 String8(sourceDesc->srcDevice()->address().c_str()),
5385 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005386 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005387 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005388 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005389 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005390 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5391 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5392 return INVALID_OPERATION;
5393 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005394 PatchBuilder patchBuilder;
5395 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5396 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005397
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005398 return connectAudioSourceToSink(
5399 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005400}
5401
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005402status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005403{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005404 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5405 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005406 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005407 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005408 return BAD_VALUE;
5409 }
5410 status_t status = disconnectAudioSource(sourceDesc);
5411
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005412 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005413 return status;
5414}
5415
Andy Hung2ddee192015-12-18 17:34:44 -08005416status_t AudioPolicyManager::setMasterMono(bool mono)
5417{
5418 if (mMasterMono == mono) {
5419 return NO_ERROR;
5420 }
5421 mMasterMono = mono;
5422 // if enabling mono we close all offloaded devices, which will invalidate the
5423 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5424 // for recreating the new AudioTrack as non-offloaded PCM.
5425 //
5426 // If disabling mono, we leave all tracks as is: we don't know which clients
5427 // and tracks are able to be recreated as offloaded. The next "song" should
5428 // play back offloaded.
5429 if (mMasterMono) {
5430 Vector<audio_io_handle_t> offloaded;
5431 for (size_t i = 0; i < mOutputs.size(); ++i) {
5432 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5433 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5434 offloaded.push(desc->mIoHandle);
5435 }
5436 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005437 for (const auto& handle : offloaded) {
5438 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005439 }
5440 }
5441 // update master mono for all remaining outputs
5442 for (size_t i = 0; i < mOutputs.size(); ++i) {
5443 updateMono(mOutputs.keyAt(i));
5444 }
5445 return NO_ERROR;
5446}
5447
5448status_t AudioPolicyManager::getMasterMono(bool *mono)
5449{
5450 *mono = mMasterMono;
5451 return NO_ERROR;
5452}
5453
Eric Laurentac9cef52017-06-09 15:46:26 -07005454float AudioPolicyManager::getStreamVolumeDB(
5455 audio_stream_type_t stream, int index, audio_devices_t device)
5456{
jiabin9a3361e2019-10-01 09:38:30 -07005457 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005458}
5459
jiabin81772902018-04-02 17:52:27 -07005460status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5461 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005462 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005463{
Kriti Dang6537def2021-03-02 13:46:59 +01005464 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5465 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005466 return BAD_VALUE;
5467 }
Kriti Dang6537def2021-03-02 13:46:59 +01005468 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5469 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005470
5471 size_t formatsWritten = 0;
5472 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005473
Kriti Dang6537def2021-03-02 13:46:59 +01005474 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005475 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5476 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005477 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005478 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005479 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005480 bool formatEnabled = true;
5481 switch (forceUse) {
5482 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005483 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005484 break;
5485 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5486 formatEnabled = false;
5487 break;
5488 default: // AUTO or ALWAYS => true
5489 break;
jiabin81772902018-04-02 17:52:27 -07005490 }
5491 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5492 }
jiabin81772902018-04-02 17:52:27 -07005493 }
5494 return NO_ERROR;
5495}
5496
Kriti Dang6537def2021-03-02 13:46:59 +01005497status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5498 audio_format_t *surroundFormats) {
5499 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5500 return BAD_VALUE;
5501 }
5502 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5503 __func__, *numSurroundFormats, surroundFormats);
5504
5505 size_t formatsWritten = 0;
5506 size_t formatsMax = *numSurroundFormats;
5507 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5508
5509 // Return formats from all device profiles that have already been resolved by
5510 // checkOutputsForDevice().
5511 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5512 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5513 audio_devices_t deviceType = device->type();
5514 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5515 // returns formats reported by HDMI devices.
5516 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5517 continue;
5518 }
5519 // Formats reported by sink devices
5520 std::unordered_set<audio_format_t> formatset;
5521 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5522 formatset.insert(it->second.begin(), it->second.end());
5523 }
5524
5525 // Formats hard-coded in the in policy configuration file (if any).
5526 FormatVector encodedFormats = device->encodedFormats();
5527 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5528 // Filter the formats which are supported by the vendor hardware.
5529 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5530 if (mConfig.getSurroundFormats().count(*it) != 0) {
5531 formats.insert(*it);
5532 } else {
5533 for (const auto& pair : mConfig.getSurroundFormats()) {
5534 if (pair.second.count(*it) != 0) {
5535 formats.insert(pair.first);
5536 break;
5537 }
5538 }
5539 }
5540 }
5541 }
5542 *numSurroundFormats = formats.size();
5543 for (const auto& format: formats) {
5544 if (formatsWritten < formatsMax) {
5545 surroundFormats[formatsWritten++] = format;
5546 }
5547 }
5548 return NO_ERROR;
5549}
5550
jiabin81772902018-04-02 17:52:27 -07005551status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5552{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005553 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005554 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5555 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005556 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005557 return BAD_VALUE;
5558 }
5559
Mikhail Naganov100f0122018-11-29 11:22:16 -08005560 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5561 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005562 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005563 return INVALID_OPERATION;
5564 }
5565
Mikhail Naganov100f0122018-11-29 11:22:16 -08005566 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005567 return NO_ERROR;
5568 }
5569
Mikhail Naganov100f0122018-11-29 11:22:16 -08005570 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005571 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005572 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005573 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005574 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005575 }
5576 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005577 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005578 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005579 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005580 }
5581 }
5582
5583 sp<SwAudioOutputDescriptor> outputDesc;
5584 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005585 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5586 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005587 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5588 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005589 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005590 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005591 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5592 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5593 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005594 name.c_str(),
5595 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005596 if (status != NO_ERROR) {
5597 continue;
5598 }
5599 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5600 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5601 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005602 name.c_str(),
5603 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005604 profileUpdated |= (status == NO_ERROR);
5605 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005606 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005607 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005608 AUDIO_DEVICE_IN_HDMI);
5609 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5610 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005611 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005612 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005613 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5614 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5615 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005616 name.c_str(),
5617 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005618 if (status != NO_ERROR) {
5619 continue;
5620 }
5621 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5622 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5623 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005624 name.c_str(),
5625 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005626 profileUpdated |= (status == NO_ERROR);
5627 }
5628
jiabin81772902018-04-02 17:52:27 -07005629 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005630 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005631 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005632 }
5633
5634 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5635}
5636
Eric Laurent5ada82e2019-08-29 17:53:54 -07005637void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005638{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005639 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005640 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005641 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005642 }
5643}
5644
jiabin6012f912018-11-02 17:06:30 -07005645bool AudioPolicyManager::isHapticPlaybackSupported()
5646{
5647 for (const auto& hwModule : mHwModules) {
5648 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5649 for (const auto &outProfile : outputProfiles) {
5650 struct audio_port audioPort;
5651 outProfile->toAudioPort(&audioPort);
5652 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5653 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5654 return true;
5655 }
5656 }
5657 }
5658 }
5659 return false;
5660}
5661
Carter Hsu325a8eb2022-01-19 19:56:51 +08005662bool AudioPolicyManager::isUltrasoundSupported()
5663{
5664 bool hasUltrasoundOutput = false;
5665 bool hasUltrasoundInput = false;
5666 for (const auto& hwModule : mHwModules) {
5667 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5668 if (!hasUltrasoundOutput) {
5669 for (const auto &outProfile : outputProfiles) {
5670 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5671 hasUltrasoundOutput = true;
5672 break;
5673 }
5674 }
5675 }
5676
5677 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5678 if (!hasUltrasoundInput) {
5679 for (const auto &inputProfile : inputProfiles) {
5680 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5681 hasUltrasoundInput = true;
5682 break;
5683 }
5684 }
5685 }
5686
5687 if (hasUltrasoundOutput && hasUltrasoundInput)
5688 return true;
5689 }
5690 return false;
5691}
5692
Atneya Nair698f5ef2022-12-15 16:15:09 -08005693bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5694{
5695 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5696 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5697 for (const auto& hwModule : mHwModules) {
5698 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5699 for (const auto &inputProfile : inputProfiles) {
5700 if ((inputProfile->getFlags() & mask) == mask) {
5701 return true;
5702 }
5703 }
5704 }
5705 return false;
5706}
5707
Eric Laurent8340e672019-11-06 11:01:08 -08005708bool AudioPolicyManager::isCallScreenModeSupported()
5709{
5710 return getConfig().isCallScreenModeSupported();
5711}
5712
5713
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005714status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005715{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005716 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005717 if (!sourceDesc->isConnected()) {
5718 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5719 return NO_ERROR;
5720 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005721 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5722 if (swOutput != 0) {
5723 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005724 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005725 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005726 }
jiabinbce0c1d2020-10-05 11:20:18 -07005727 if (releaseOutput(sourceDesc->portId())) {
5728 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5729 // no need to release audio patch here but just return NO_ERROR.
5730 return NO_ERROR;
5731 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005732 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005733 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005734 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005735 // close Hwoutput and remove from mHwOutputs
5736 } else {
5737 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5738 }
5739 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005740 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005741 sourceDesc->disconnect();
5742 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005743}
5744
François Gaffiec005e562018-11-06 15:04:49 +01005745sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5746 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005747{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005748 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005749 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005750 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005751 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005752 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5753 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005754 source = sourceDesc;
5755 break;
5756 }
5757 }
5758 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005759}
5760
Eric Laurentb4f42a92022-01-17 17:37:31 +01005761bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005762 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005763 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005764{
5765 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5766 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005767 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005768 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005769 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5770 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5771 return false;
5772 }
5773 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5774 return false;
5775 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005776 }
5777
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005778 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005779 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005780 if (profile == nullptr) {
5781 return false;
5782 }
5783
5784 // The caller can have the audio config criteria ignored by either passing a null ptr or
5785 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005786 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005787 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005788
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005789 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005790 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005791 return false;
5792 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005793 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005794 return true;
5795}
5796
5797void AudioPolicyManager::checkVirtualizerClientRoutes() {
5798 std::set<audio_stream_type_t> streamsToInvalidate;
5799 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005800 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5801 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005802 audio_attributes_t attr = client->attributes();
5803 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5804 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5805 audio_config_base_t clientConfig = client->config();
5806 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005807 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005808 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005809 streamsToInvalidate.insert(client->stream());
5810 }
5811 }
5812 }
5813
jiabinc44b3462022-12-08 12:52:31 -08005814 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005815}
5816
Eric Laurente191d1b2022-04-15 11:59:25 +02005817
5818bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5819 const sp<SwAudioOutputDescriptor>& outputDesc) {
5820 if (outputDesc->isDuplicated()) {
5821 return false;
5822 }
5823 DeviceVector devices = outputDesc->supportedDevices();
5824 for (size_t i = 0; i < mOutputs.size(); i++) {
5825 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5826 if (desc == outputDesc || desc->isDuplicated()) {
5827 continue;
5828 }
5829 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5830 if (!sharedDevices.isEmpty()
5831 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5832 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5833 return false;
5834 }
5835 }
5836 return true;
5837}
5838
5839
Eric Laurentfa0f6742021-08-17 18:39:44 +02005840status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005841 const audio_attributes_t *attr,
5842 audio_io_handle_t *output) {
5843 *output = AUDIO_IO_HANDLE_NONE;
5844
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005845 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5846 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5847 audio_config_t *configPtr = nullptr;
5848 audio_config_t config;
5849 if (mixerConfig != nullptr) {
5850 config = audio_config_initializer(mixerConfig);
5851 configPtr = &config;
5852 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005853 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005854 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005855 return BAD_VALUE;
5856 }
5857
5858 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005859 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005860 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005861 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005862 return BAD_VALUE;
5863 }
5864
Eric Laurente191d1b2022-04-15 11:59:25 +02005865 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005866 for (size_t i = 0; i < mOutputs.size(); i++) {
5867 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005868 if (!desc->isDuplicated()
5869 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5870 spatializerOutputs.push_back(desc);
5871 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005872 }
5873 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005874 mSpatializerOutput.clear();
5875 bool outputsChanged = false;
5876 for (const auto& desc : spatializerOutputs) {
5877 if (desc->mProfile == profile
5878 && (configPtr == nullptr
5879 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5880 mSpatializerOutput = desc;
5881 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5882 } else {
5883 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5884 " and devices %s", __func__, desc->mIoHandle,
5885 configPtr != nullptr ? configPtr->channel_mask : 0,
5886 devices.toString().c_str());
5887 closeOutput(desc->mIoHandle);
5888 outputsChanged = true;
5889 }
Eric Laurent39095982021-08-24 18:29:27 +02005890 }
5891
Eric Laurente191d1b2022-04-15 11:59:25 +02005892 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005893 sp<SwAudioOutputDescriptor> desc =
5894 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005895 if (desc != nullptr) {
5896 mSpatializerOutput = desc;
5897 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005898 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005899 }
5900
5901 checkVirtualizerClientRoutes();
5902
Eric Laurente191d1b2022-04-15 11:59:25 +02005903 if (outputsChanged) {
5904 mPreviousOutputs = mOutputs;
5905 mpClientInterface->onAudioPortListUpdate();
5906 }
5907
5908 if (mSpatializerOutput == nullptr) {
5909 ALOGV("%s could not open spatializer output with requested config", __func__);
5910 return BAD_VALUE;
5911 }
Eric Laurent39095982021-08-24 18:29:27 +02005912 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005913 ALOGV("%s returning new spatializer output %d", __func__, *output);
5914 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005915}
5916
Eric Laurentfa0f6742021-08-17 18:39:44 +02005917status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5918 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005919 return INVALID_OPERATION;
5920 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005921 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005922 return BAD_VALUE;
5923 }
Eric Laurent39095982021-08-24 18:29:27 +02005924
Eric Laurente191d1b2022-04-15 11:59:25 +02005925 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5926 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5927 closeOutput(mSpatializerOutput->mIoHandle);
5928 //from now on mSpatializerOutput is null
5929 checkVirtualizerClientRoutes();
5930 }
Eric Laurent39095982021-08-24 18:29:27 +02005931
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005932 return NO_ERROR;
5933}
5934
Eric Laurente552edb2014-03-10 17:42:56 -07005935// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005936// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005937// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005938uint32_t AudioPolicyManager::nextAudioPortGeneration()
5939{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005940 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005941}
5942
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005943static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005944 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5945 !audioPolicyXmlConfigFile.empty()) {
5946 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5947 if (ret == NO_ERROR) {
5948 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005949 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005950 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005951 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005952 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005953}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005954
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005955AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5956 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005957 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005958 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005959 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005960 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005961 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005962 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005963 mAudioPortGeneration(1),
5964 mBeaconMuteRefCount(0),
5965 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005966 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005967 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005968 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005969 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005970{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005971}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005972
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005973AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5974 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5975{
5976 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005977}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005978
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005979void AudioPolicyManager::loadConfig() {
5980 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005981 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005982 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005983 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005984}
5985
5986status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005987 {
5988 auto engLib = EngineLibrary::load(
5989 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5990 if (!engLib) {
5991 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5992 return NO_INIT;
5993 }
5994 mEngine = engLib->createEngine();
5995 if (mEngine == nullptr) {
5996 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5997 return NO_INIT;
5998 }
François Gaffie2110e042015-03-24 08:41:51 +01005999 }
6000 mEngine->setObserver(this);
6001 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006002 if (status != NO_ERROR) {
6003 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6004 return status;
6005 }
François Gaffie2110e042015-03-24 08:41:51 +01006006
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006007 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006008 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6009 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6010
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006011 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006012 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006013 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006014
Eric Laurent3a4311c2014-03-17 12:00:47 -07006015 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01006016 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
6017 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
6018 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006019 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006020 }
jiabin9ff780e2018-03-19 18:19:52 -07006021 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07006022 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07006023 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07006024 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07006025 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07006026 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07006027 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07006028 }
6029 }
6030 }
Eric Laurente552edb2014-03-10 17:42:56 -07006031
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006032 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006033
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006034 // Silence ALOGV statements
6035 property_set("log.tag." LOG_TAG, "D");
6036
Eric Laurente552edb2014-03-10 17:42:56 -07006037 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006038 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006039}
6040
Eric Laurente0720872014-03-11 09:30:41 -07006041AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006042{
Eric Laurente552edb2014-03-10 17:42:56 -07006043 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006044 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006045 }
6046 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006047 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006048 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006049 mAvailableOutputDevices.clear();
6050 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006051 mOutputs.clear();
6052 mInputs.clear();
6053 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08006054 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006055 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006056}
6057
Eric Laurente0720872014-03-11 09:30:41 -07006058status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006059{
Eric Laurent87ffa392015-05-22 10:32:38 -07006060 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006061}
6062
Eric Laurente552edb2014-03-10 17:42:56 -07006063// ---
6064
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006065void AudioPolicyManager::onNewAudioModulesAvailable()
6066{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006067 DeviceVector newDevices;
6068 onNewAudioModulesAvailableInt(&newDevices);
6069 if (!newDevices.empty()) {
6070 nextAudioPortGeneration();
6071 mpClientInterface->onAudioPortListUpdate();
6072 }
6073}
6074
6075void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6076{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006077 for (const auto& hwModule : mHwModulesAll) {
6078 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6079 continue;
6080 }
6081 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
6082 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
6083 ALOGW("could not open HW module %s", hwModule->getName());
6084 continue;
6085 }
6086 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006087 // open all output streams needed to access attached devices.
6088 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006089 // This also validates mAvailableOutputDevices list
6090 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6091 if (!outProfile->canOpenNewIo()) {
6092 ALOGE("Invalid Output profile max open count %u for profile %s",
6093 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6094 continue;
6095 }
6096 if (!outProfile->hasSupportedDevices()) {
6097 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6098 continue;
6099 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006100 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6101 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006102 mTtsOutputAvailable = true;
6103 }
6104
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006105 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
6106 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
6107 sp<DeviceDescriptor> supportedDevice = 0;
6108 if (supportedDevices.contains(mDefaultOutputDevice)) {
6109 supportedDevice = mDefaultOutputDevice;
6110 } else {
6111 // choose first device present in profile's SupportedDevices also part of
6112 // mAvailableOutputDevices.
6113 if (availProfileDevices.isEmpty()) {
6114 continue;
6115 }
6116 supportedDevice = availProfileDevices.itemAt(0);
6117 }
6118 if (!mOutputDevicesAll.contains(supportedDevice)) {
6119 continue;
6120 }
6121 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6122 mpClientInterface);
6123 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006124 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6125 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006126 AUDIO_STREAM_DEFAULT,
6127 AUDIO_OUTPUT_FLAG_NONE, &output);
6128 if (status != NO_ERROR) {
6129 ALOGW("Cannot open output stream for devices %s on hw module %s",
6130 supportedDevice->toString().c_str(), hwModule->getName());
6131 continue;
6132 }
6133 for (const auto &device : availProfileDevices) {
6134 // give a valid ID to an attached device once confirmed it is reachable
6135 if (!device->isAttached()) {
6136 device->attach(hwModule);
6137 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006138 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006139 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006140 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6141 }
6142 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006143 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006144 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6145 mPrimaryOutput = outputDesc;
6146 }
Eric Laurent39095982021-08-24 18:29:27 +02006147 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006148 outputDesc->close();
6149 } else {
6150 addOutput(output, outputDesc);
6151 setOutputDevices(outputDesc,
6152 DeviceVector(supportedDevice),
6153 true,
6154 0,
6155 NULL);
6156 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006157 }
6158 // open input streams needed to access attached devices to validate
6159 // mAvailableInputDevices list
6160 for (const auto& inProfile : hwModule->getInputProfiles()) {
6161 if (!inProfile->canOpenNewIo()) {
6162 ALOGE("Invalid Input profile max open count %u for profile %s",
6163 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6164 continue;
6165 }
6166 if (!inProfile->hasSupportedDevices()) {
6167 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6168 continue;
6169 }
6170 // chose first device present in profile's SupportedDevices also part of
6171 // available input devices
6172 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
6173 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
6174 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006175 ALOGV("%s: Input device list is empty! for profile %s",
6176 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006177 continue;
6178 }
6179 sp<AudioInputDescriptor> inputDesc =
6180 new AudioInputDescriptor(inProfile, mpClientInterface);
6181
6182 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6183 status_t status = inputDesc->open(nullptr,
6184 availProfileDevices.itemAt(0),
6185 AUDIO_SOURCE_MIC,
6186 AUDIO_INPUT_FLAG_NONE,
6187 &input);
6188 if (status != NO_ERROR) {
6189 ALOGW("Cannot open input stream for device %s on hw module %s",
6190 availProfileDevices.toString().c_str(),
6191 hwModule->getName());
6192 continue;
6193 }
6194 for (const auto &device : availProfileDevices) {
6195 // give a valid ID to an attached device once confirmed it is reachable
6196 if (!device->isAttached()) {
6197 device->attach(hwModule);
6198 device->importAudioPortAndPickAudioProfile(inProfile, true);
6199 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006200 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006201 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6202 }
6203 }
6204 inputDesc->close();
6205 }
6206 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006207
6208 // Check if spatializer outputs can be closed until used.
6209 // mOutputs vector never contains duplicated outputs at this point.
6210 std::vector<audio_io_handle_t> outputsClosed;
6211 for (size_t i = 0; i < mOutputs.size(); i++) {
6212 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6213 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6214 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6215 outputsClosed.push_back(desc->mIoHandle);
6216 desc->close();
6217 }
6218 }
6219 for (auto output : outputsClosed) {
6220 removeOutput(output);
6221 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006222}
6223
Eric Laurent98e38192018-02-15 18:31:53 -08006224void AudioPolicyManager::addOutput(audio_io_handle_t output,
6225 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006226{
Eric Laurent1c333e22014-05-20 10:48:17 -07006227 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006228 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006229 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006230 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006231 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006232}
6233
François Gaffie53615e22015-03-19 09:24:12 +01006234void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6235{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006236 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6237 ALOGV("%s: removing primary output", __func__);
6238 mPrimaryOutput = nullptr;
6239 }
François Gaffie53615e22015-03-19 09:24:12 +01006240 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006241 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006242}
6243
Eric Laurent98e38192018-02-15 18:31:53 -08006244void AudioPolicyManager::addInput(audio_io_handle_t input,
6245 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006246{
Eric Laurent1c333e22014-05-20 10:48:17 -07006247 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006248 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006249}
Eric Laurente552edb2014-03-10 17:42:56 -07006250
François Gaffie11d30102018-11-02 16:09:09 +01006251status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006252 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006253 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006254{
François Gaffie11d30102018-11-02 16:09:09 +01006255 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006256 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006257 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006258
François Gaffie11d30102018-11-02 16:09:09 +01006259 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006260 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006261 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006262 }
Eric Laurente552edb2014-03-10 17:42:56 -07006263
Eric Laurent3b73df72014-03-11 09:06:29 -07006264 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006265 // first call getAudioPort to get the supported attributes from the HAL
6266 struct audio_port_v7 port = {};
6267 device->toAudioPort(&port);
6268 status_t status = mpClientInterface->getAudioPort(&port);
6269 if (status == NO_ERROR) {
6270 device->importAudioPort(port);
6271 }
6272
6273 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006274 for (size_t i = 0; i < mOutputs.size(); i++) {
6275 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006276 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006277 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006278 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6279 mOutputs.keyAt(i), device->toString().c_str());
6280 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006281 }
6282 }
6283 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006284 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006285 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006286 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6287 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006288 if (profile->supportsDevice(device)) {
6289 profiles.add(profile);
6290 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6291 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006292 }
6293 }
6294 }
6295
Eric Laurent7b279bb2015-12-14 10:18:23 -08006296 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006297
Eric Laurente552edb2014-03-10 17:42:56 -07006298 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006299 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006300 return BAD_VALUE;
6301 }
6302
6303 // open outputs for matching profiles if needed. Direct outputs are also opened to
6304 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6305 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006306 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006307
6308 // nothing to do if one output is already opened for this profile
6309 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006310 for (j = 0; j < outputs.size(); j++) {
6311 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006312 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006313 // matching profile: save the sample rates, format and channel masks supported
6314 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006315 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006316 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006317 }
Eric Laurente552edb2014-03-10 17:42:56 -07006318 break;
6319 }
6320 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006321 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006322 continue;
6323 }
6324
Eric Laurent3974e3b2017-12-07 17:58:43 -08006325 if (!profile->canOpenNewIo()) {
6326 ALOGW("Max Output number %u already opened for this profile %s",
6327 profile->maxOpenCount, profile->getTagName().c_str());
6328 continue;
6329 }
6330
Eric Laurent83efe1c2017-07-09 16:51:08 -07006331 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07006332 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006333 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6334 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006335 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006336 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006337 profiles.removeAt(profile_index);
6338 profile_index--;
6339 } else {
6340 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006341 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006342 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006343 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6344 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006345 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006346 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006347
François Gaffie11d30102018-11-02 16:09:09 +01006348 if (device_distinguishes_on_address(deviceType)) {
6349 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6350 device->toString().c_str());
6351 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
6352 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006353 }
Eric Laurente552edb2014-03-10 17:42:56 -07006354 ALOGV("checkOutputsForDevice(): adding output %d", output);
6355 }
6356 }
6357
6358 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006359 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006360 return BAD_VALUE;
6361 }
Eric Laurentd4692962014-05-05 18:13:44 -07006362 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006363 // check if one opened output is not needed any more after disconnecting one device
6364 for (size_t i = 0; i < mOutputs.size(); i++) {
6365 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006366 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006367 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006368 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006369 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006370 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006371 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006372 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6373 mOutputs.keyAt(i));
6374 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006375 }
Eric Laurente552edb2014-03-10 17:42:56 -07006376 }
6377 }
Eric Laurentd4692962014-05-05 18:13:44 -07006378 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006379 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006380 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6381 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006382 if (!profile->supportsDevice(device)) {
6383 continue;
6384 }
6385 ALOGV("checkOutputsForDevice(): "
6386 "clearing direct output profile %zu on module %s",
6387 j, hwModule->getName());
6388 profile->clearAudioProfiles();
6389 if (!profile->hasDynamicAudioProfile()) {
6390 continue;
6391 }
6392 // When a device is disconnected, if there is an IOProfile that contains dynamic
6393 // profiles and supports the disconnected device, call getAudioPort to repopulate
6394 // the capabilities of the devices that is supported by the IOProfile.
6395 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6396 if (supportedDevice == device ||
6397 !mAvailableOutputDevices.contains(supportedDevice)) {
6398 continue;
6399 }
6400 struct audio_port_v7 port;
6401 supportedDevice->toAudioPort(&port);
6402 status_t status = mpClientInterface->getAudioPort(&port);
6403 if (status == NO_ERROR) {
6404 supportedDevice->importAudioPort(port);
6405 }
Eric Laurente552edb2014-03-10 17:42:56 -07006406 }
6407 }
6408 }
6409 }
6410 return NO_ERROR;
6411}
6412
François Gaffie11d30102018-11-02 16:09:09 +01006413status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006414 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006415{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006416 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006417
François Gaffie11d30102018-11-02 16:09:09 +01006418 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006419 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006420 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006421 }
6422
Eric Laurentd4692962014-05-05 18:13:44 -07006423 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006424 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006425 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006426 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006427 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006428 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006429 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006430 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006431
François Gaffie11d30102018-11-02 16:09:09 +01006432 if (profile->supportsDevice(device)) {
6433 profiles.add(profile);
6434 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6435 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006436 }
6437 }
6438 }
6439
Eric Laurent0dd51852019-04-19 18:18:58 -07006440 if (profiles.isEmpty()) {
6441 ALOGW("%s: No input profile available for device %s",
6442 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006443 return BAD_VALUE;
6444 }
6445
6446 // open inputs for matching profiles if needed. Direct inputs are also opened to
6447 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6448 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6449
Eric Laurent1c333e22014-05-20 10:48:17 -07006450 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006451
Eric Laurentd4692962014-05-05 18:13:44 -07006452 // nothing to do if one input is already opened for this profile
6453 size_t input_index;
6454 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6455 desc = mInputs.valueAt(input_index);
6456 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006457 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006458 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006459 }
Eric Laurentd4692962014-05-05 18:13:44 -07006460 break;
6461 }
6462 }
6463 if (input_index != mInputs.size()) {
6464 continue;
6465 }
6466
Eric Laurent3974e3b2017-12-07 17:58:43 -08006467 if (!profile->canOpenNewIo()) {
6468 ALOGW("Max Input number %u already opened for this profile %s",
6469 profile->maxOpenCount, profile->getTagName().c_str());
6470 continue;
6471 }
6472
Eric Laurentfe231122017-11-17 17:48:06 -08006473 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006474 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006475 status_t status = desc->open(nullptr,
6476 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006477 AUDIO_SOURCE_MIC,
6478 AUDIO_INPUT_FLAG_NONE,
6479 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006480
Eric Laurentcf2c0212014-07-25 16:20:43 -07006481 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006482 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006483 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006484 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006485 mpClientInterface->setParameters(input, String8(param));
6486 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006487 }
François Gaffie11d30102018-11-02 16:09:09 +01006488 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006489 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006490 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006491 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006492 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006493 }
6494
Eric Laurent0dd51852019-04-19 18:18:58 -07006495 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006496 addInput(input, desc);
6497 }
6498 } // endif input != 0
6499
Eric Laurentcf2c0212014-07-25 16:20:43 -07006500 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006501 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006502 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006503 profiles.removeAt(profile_index);
6504 profile_index--;
6505 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006506 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006507 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006508 }
Eric Laurentd4692962014-05-05 18:13:44 -07006509 ALOGV("checkInputsForDevice(): adding input %d", input);
6510 }
6511 } // end scan profiles
6512
6513 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006514 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006515 return BAD_VALUE;
6516 }
6517 } else {
6518 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006519 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006520 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006521 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006522 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006523 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006524 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006525 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006526 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6527 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006528 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006529 }
6530 }
6531 }
6532 } // end disconnect
6533
6534 return NO_ERROR;
6535}
6536
6537
Eric Laurente0720872014-03-11 09:30:41 -07006538void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006539{
6540 ALOGV("closeOutput(%d)", output);
6541
François Gaffie1c878552018-11-22 16:53:21 +01006542 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6543 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006544 ALOGW("closeOutput() unknown output %d", output);
6545 return;
6546 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006547 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006548 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006549
Eric Laurente552edb2014-03-10 17:42:56 -07006550 // look for duplicated outputs connected to the output being removed.
6551 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006552 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6553 if (dupOutput->isDuplicated() &&
6554 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6555 sp<SwAudioOutputDescriptor> remainingOutput =
6556 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006557 // As all active tracks on duplicated output will be deleted,
6558 // and as they were also referenced on the other output, the reference
6559 // count for their stream type must be adjusted accordingly on
6560 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006561 const bool wasActive = remainingOutput->isActive();
6562 // Note: no-op on the closing output where all clients has already been set inactive
6563 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006564 // stop() will be a no op if the output is still active but is needed in case all
6565 // active streams refcounts where cleared above
6566 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006567 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006568 }
Eric Laurente552edb2014-03-10 17:42:56 -07006569 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6570 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6571
6572 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006573 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006574 }
6575 }
6576
Eric Laurent05b90f82014-08-27 15:32:29 -07006577 nextAudioPortGeneration();
6578
François Gaffie1c878552018-11-22 16:53:21 +01006579 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006580 if (index >= 0) {
6581 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006582 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6583 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006584 mAudioPatches.removeItemsAt(index);
6585 mpClientInterface->onAudioPatchListUpdate();
6586 }
6587
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006588 if (closingOutputWasActive) {
6589 closingOutput->stop();
6590 }
François Gaffie1c878552018-11-22 16:53:21 +01006591 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006592
François Gaffie53615e22015-03-19 09:24:12 +01006593 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006594 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006595 if (closingOutput == mSpatializerOutput) {
6596 mSpatializerOutput.clear();
6597 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006598
6599 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6600 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006601 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006602 bool directOutputOpen = false;
6603 for (size_t i = 0; i < mOutputs.size(); i++) {
6604 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6605 directOutputOpen = true;
6606 break;
6607 }
6608 }
6609 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006610 ALOGV("no direct outputs open, reset MSD patches");
6611 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6612 // how output devices for patching are resolved. Avoid by caching and reusing the
6613 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6614 // devices to patch to. This may be complicated by the fact that devices may become
6615 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006616 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006617 }
6618 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006619}
6620
6621void AudioPolicyManager::closeInput(audio_io_handle_t input)
6622{
6623 ALOGV("closeInput(%d)", input);
6624
6625 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6626 if (inputDesc == NULL) {
6627 ALOGW("closeInput() unknown input %d", input);
6628 return;
6629 }
6630
Eric Laurent6a94d692014-05-20 11:18:06 -07006631 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006632
François Gaffie11d30102018-11-02 16:09:09 +01006633 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006634 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006635 if (index >= 0) {
6636 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006637 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6638 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006639 mAudioPatches.removeItemsAt(index);
6640 mpClientInterface->onAudioPatchListUpdate();
6641 }
6642
Eric Laurentfe231122017-11-17 17:48:06 -08006643 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006644 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006645
François Gaffie11d30102018-11-02 16:09:09 +01006646 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6647 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006648 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006649 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006650 }
Eric Laurente552edb2014-03-10 17:42:56 -07006651}
6652
François Gaffie11d30102018-11-02 16:09:09 +01006653SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6654 const DeviceVector &devices,
6655 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006656{
6657 SortedVector<audio_io_handle_t> outputs;
6658
François Gaffie11d30102018-11-02 16:09:09 +01006659 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006660 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006661 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006662 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006663 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006664 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006665 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006666 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006667 outputs.add(openOutputs.keyAt(i));
6668 }
6669 }
6670 return outputs;
6671}
6672
Mikhail Naganov37977152018-07-11 15:54:44 -07006673void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6674{
6675 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6676 // output is suspended before any tracks are moved to it
6677 checkA2dpSuspend();
6678 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006679 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006680 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006681 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006682 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006683 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6684 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6685 // configuration changes will ultimately be rerouted correctly. We can still avoid
6686 // unnecessary rerouting by caching and reusing the arguments to
6687 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6688 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006689 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006690 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006691 // an event that changed routing likely occurred, inform upper layers
6692 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006693}
6694
François Gaffiec005e562018-11-06 15:04:49 +01006695bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6696 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006697{
François Gaffiec005e562018-11-06 15:04:49 +01006698 return mEngine->getProductStrategyForAttributes(lAttr) ==
6699 mEngine->getProductStrategyForAttributes(rAttr);
6700}
6701
Francois Gaffieff1eb522020-05-06 18:37:04 +02006702void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6703{
6704 for (size_t i = 0; i < mAudioSources.size(); i++) {
6705 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6706 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006707 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006708 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006709 connectAudioSource(sourceDesc);
6710 }
6711 }
6712}
6713
6714void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6715{
6716 for (size_t i = 0; i < mAudioSources.size(); i++) {
6717 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6718 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6719 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6720 disconnectAudioSource(sourceDesc);
6721 }
6722 }
6723}
6724
François Gaffiec005e562018-11-06 15:04:49 +01006725void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6726{
6727 auto psId = mEngine->getProductStrategyForAttributes(attr);
6728
6729 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6730 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006731
François Gaffie11d30102018-11-02 16:09:09 +01006732 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6733 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006734
Eric Laurentc209fe42020-06-05 18:11:23 -07006735 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006736 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006737 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006738 // take into account dynamic audio policies related changes: if a client is now associated
6739 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006740 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006741 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6742 if (desc->isDuplicated()) {
6743 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006744 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006745 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6746 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6747 continue;
6748 }
6749 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006750 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006751 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6752 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6753 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006754 if (status != OK) {
6755 continue;
6756 }
yucliuf4de36d2020-09-14 14:57:56 -07006757 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006758 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006759 maxLatency = desc->latency();
6760 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006761 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006762 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006763 }
6764 }
6765
Eric Laurent56ed8842022-11-15 16:04:41 +01006766 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006767 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6768 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006769 for (audio_io_handle_t srcOut : srcOutputs) {
6770 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006771 if (desc == nullptr) continue;
6772
6773 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006774 maxLatency = desc->latency();
6775 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006776
Eric Laurent56ed8842022-11-15 16:04:41 +01006777 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006778 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006779 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006780 // a client on a non direct outputs has necessarily a linear PCM format
6781 // so we can call selectOutput() safely
6782 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6783 client->flags(),
6784 client->config().format,
6785 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006786 client->config().sample_rate,
6787 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006788 if (newOutput != srcOut) {
6789 invalidate = true;
6790 break;
6791 }
6792 } else {
6793 sp<IOProfile> profile = getProfileForOutput(newDevices,
6794 client->config().sample_rate,
6795 client->config().format,
6796 client->config().channel_mask,
6797 client->flags(),
6798 true /* directOnly */);
6799 if (profile != desc->mProfile) {
6800 invalidate = true;
6801 break;
6802 }
6803 }
6804 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006805 // mute strategy while moving tracks from one output to another
6806 if (invalidate) {
6807 invalidatedOutputs.push_back(desc);
6808 if (desc->isStrategyActive(psId)) {
6809 setStrategyMute(psId, true, desc);
6810 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6811 newDevices.types());
6812 }
Eric Laurente552edb2014-03-10 17:42:56 -07006813 }
François Gaffiec005e562018-11-06 15:04:49 +01006814 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006815 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006816 connectAudioSource(source);
6817 }
Eric Laurente552edb2014-03-10 17:42:56 -07006818 }
6819
Eric Laurent56ed8842022-11-15 16:04:41 +01006820 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6821 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6822 std::to_string(srcOutputs[0]).c_str(),
6823 std::to_string(dstOutputs[0]).c_str());
6824
François Gaffiec005e562018-11-06 15:04:49 +01006825 // Move effects associated to this stream from previous output to new output
6826 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006827 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006828 }
François Gaffiec005e562018-11-06 15:04:49 +01006829 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006830 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006831 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006832 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006833 desc->setTracksInvalidatedStatusByStrategy(psId);
6834 }
Eric Laurente552edb2014-03-10 17:42:56 -07006835 }
6836 }
6837}
6838
Eric Laurente0720872014-03-11 09:30:41 -07006839void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006840{
François Gaffiec005e562018-11-06 15:04:49 +01006841 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6842 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6843 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006844 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006845 }
Eric Laurente552edb2014-03-10 17:42:56 -07006846}
6847
Kevin Rocard153f92d2018-12-18 18:33:28 -08006848void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08006849 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006850 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006851 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006852 for (size_t i = 0; i < mOutputs.size(); i++) {
6853 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6854 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006855 sp<AudioPolicyMix> primaryMix;
6856 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006857 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006858 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6859 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
6860 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006861 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6862 for (auto &secondaryMix : secondaryMixes) {
6863 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6864 if (outputDesc != nullptr &&
6865 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6866 secondaryDescs.push_back(outputDesc);
6867 }
6868 }
6869
jiabinc44b3462022-12-08 12:52:31 -08006870 if (status != OK &&
6871 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
6872 // When it failed to query secondary output, only invalidate the client that is not
6873 // MMAP. The reason is that MMAP stream will not support secondary output.
6874 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00006875 } else if (!std::equal(
6876 client->getSecondaryOutputs().begin(),
6877 client->getSecondaryOutputs().end(),
6878 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006879 if (!audio_is_linear_pcm(client->config().format)) {
6880 // If the format is not PCM, the tracks should be invalidated to get correct
6881 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08006882 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00006883 } else {
6884 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6885 std::vector<audio_io_handle_t> secondaryOutputIds;
6886 for (const auto &secondaryDesc: secondaryDescs) {
6887 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6888 weakSecondaryDescs.push_back(secondaryDesc);
6889 }
6890 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6891 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006892 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006893 }
6894 }
6895 }
jiabin10a03f12021-05-07 23:46:28 +00006896 if (!trackSecondaryOutputs.empty()) {
6897 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6898 }
jiabinc44b3462022-12-08 12:52:31 -08006899 if (!clientsToInvalidate.empty()) {
6900 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
6901 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006902 }
6903}
6904
Eric Laurent2517af32020-11-25 15:31:27 +01006905bool AudioPolicyManager::isScoRequestedForComm() const {
6906 AudioDeviceTypeAddrVector devices;
6907 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6908 for (const auto &device : devices) {
6909 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6910 return true;
6911 }
6912 }
6913 return false;
6914}
6915
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006916bool AudioPolicyManager::isHearingAidUsedForComm() const {
6917 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6918 true /*fromCache*/);
6919 for (const auto &device : devices) {
6920 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6921 return true;
6922 }
6923 }
6924 return false;
6925}
6926
6927
Eric Laurente0720872014-03-11 09:30:41 -07006928void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006929{
François Gaffie53615e22015-03-19 09:24:12 +01006930 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006931 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006932 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006933 return;
6934 }
6935
Eric Laurent3a4311c2014-03-17 12:00:47 -07006936 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006937 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6938 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006939 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006940
6941 // if suspended, restore A2DP output if:
6942 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006943 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006944 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006945 //
Eric Laurentf732e072016-08-03 19:30:28 -07006946 // if not suspended, suspend A2DP output if:
6947 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006948 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006949 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006950 //
6951 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006952 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006953 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006954 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006955 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006956
6957 mpClientInterface->restoreOutput(a2dpOutput);
6958 mA2dpSuspended = false;
6959 }
6960 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006961 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006962 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006963 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006964 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006965
6966 mpClientInterface->suspendOutput(a2dpOutput);
6967 mA2dpSuspended = true;
6968 }
6969 }
6970}
6971
François Gaffie11d30102018-11-02 16:09:09 +01006972DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6973 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006974{
François Gaffie11d30102018-11-02 16:09:09 +01006975 DeviceVector devices;
6976
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006977 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006978 if (index >= 0) {
6979 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006980 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006981 ALOGV("%s device %s forced by patch %d", __func__,
6982 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6983 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006984 }
6985 }
6986
Dean Wheatley514b4312020-06-17 21:45:00 +10006987 // Do not retrieve engine device for outputs through MSD
6988 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6989 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6990 return outputDesc->devices();
6991 }
6992
Eric Laurent97ac8712018-07-27 18:59:02 -07006993 // Honor explicit routing requests only if no client using default routing is active on this
6994 // input: a specific app can not force routing for other apps by setting a preferred device.
6995 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006996 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006997 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006998 if (device != nullptr) {
6999 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007000 }
7001
François Gaffiea807ef92018-11-05 10:44:33 +01007002 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7003 // of setForceUse / Default Bus device here
7004 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7005 if (device != nullptr) {
7006 return DeviceVector(device);
7007 }
7008
François Gaffiec005e562018-11-06 15:04:49 +01007009 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7010 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7011 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307012 auto hasStreamActive = [&](auto stream) {
7013 return hasStream(streams, stream) && isStreamActive(stream, 0);
7014 };
Eric Laurent484e9272018-06-07 17:29:23 -07007015
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307016 auto doGetOutputDevicesForVoice = [&]() {
7017 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007018 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307019 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007020 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7021 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307022 };
7023
7024 // With low-latency playing on speaker, music on WFD, when the first low-latency
7025 // output is stopped, getNewOutputDevices checks for a product strategy
7026 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007027 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307028 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7029 // stream is associated to the output descriptor.
7030 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7031 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7032 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7033 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007034 // Retrieval of devices for voice DL is done on primary output profile, cannot
7035 // check the route (would force modifying configuration file for this profile)
7036 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7037 break;
7038 }
Eric Laurente552edb2014-03-10 17:42:56 -07007039 }
François Gaffiec005e562018-11-06 15:04:49 +01007040 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007041 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007042}
7043
François Gaffie11d30102018-11-02 16:09:09 +01007044sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7045 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007046{
François Gaffie11d30102018-11-02 16:09:09 +01007047 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007048
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007049 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007050 if (index >= 0) {
7051 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007052 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007053 ALOGV("getNewInputDevice() device %s forced by patch %d",
7054 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7055 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007056 }
7057 }
7058
Eric Laurent97ac8712018-07-27 18:59:02 -07007059 // Honor explicit routing requests only if no client using default routing is active on this
7060 // input: a specific app can not force routing for other apps by setting a preferred device.
7061 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007062 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7063 if (device != nullptr) {
7064 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007065 }
7066
Eric Laurentdc95a252018-04-12 12:46:56 -07007067 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007068 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007069 audio_attributes_t attributes;
7070 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007071 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007072 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7073 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007074 attributes = topClient->attributes();
7075 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007076 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007077 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007078 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7079 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007080 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007081 }
7082
Francois Gaffie716e1432019-01-14 16:58:59 +01007083 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7084 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007085 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007086 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007087 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007088 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007089
Eric Laurente552edb2014-03-10 17:42:56 -07007090 return device;
7091}
7092
Eric Laurent794fde22016-03-11 09:50:45 -08007093bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7094 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007095 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007096}
7097
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007098status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007099 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007100 if (devices == nullptr) {
7101 return BAD_VALUE;
7102 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007103
Andy Hung6d23c0f2022-02-16 09:37:15 -08007104 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007105 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7106 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007107 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007108 for (const auto& device : curDevices) {
7109 devices->push_back(device->getDeviceTypeAddr());
7110 }
7111 return NO_ERROR;
7112}
7113
Eric Laurente0720872014-03-11 09:30:41 -07007114void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007115 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007116 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007117 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007118 updateDevicesAndOutputs();
7119 break;
7120 default:
7121 break;
7122 }
7123}
7124
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007125uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007126
7127 // skip beacon mute management if a dedicated TTS output is available
7128 if (mTtsOutputAvailable) {
7129 return 0;
7130 }
7131
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007132 switch(event) {
7133 case STARTING_OUTPUT:
7134 mBeaconMuteRefCount++;
7135 break;
7136 case STOPPING_OUTPUT:
7137 if (mBeaconMuteRefCount > 0) {
7138 mBeaconMuteRefCount--;
7139 }
7140 break;
7141 case STARTING_BEACON:
7142 mBeaconPlayingRefCount++;
7143 break;
7144 case STOPPING_BEACON:
7145 if (mBeaconPlayingRefCount > 0) {
7146 mBeaconPlayingRefCount--;
7147 }
7148 break;
7149 }
7150
7151 if (mBeaconMuteRefCount > 0) {
7152 // any playback causes beacon to be muted
7153 return setBeaconMute(true);
7154 } else {
7155 // no other playback: unmute when beacon starts playing, mute when it stops
7156 return setBeaconMute(mBeaconPlayingRefCount == 0);
7157 }
7158}
7159
7160uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7161 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7162 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7163 // keep track of muted state to avoid repeating mute/unmute operations
7164 if (mBeaconMuted != mute) {
7165 // mute/unmute AUDIO_STREAM_TTS on all outputs
7166 ALOGV("\t muting %d", mute);
7167 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007168 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7169 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7170 ALOGV("\t no tts volume source available");
7171 return 0;
7172 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007173 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007174 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007175 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007176 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007177 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007178 maxLatency = latency;
7179 }
7180 }
7181 mBeaconMuted = mute;
7182 return maxLatency;
7183 }
7184 return 0;
7185}
7186
Eric Laurente0720872014-03-11 09:30:41 -07007187void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007188{
François Gaffiec005e562018-11-06 15:04:49 +01007189 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007190 mPreviousOutputs = mOutputs;
7191}
7192
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007193uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007194 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007195 uint32_t delayMs)
7196{
7197 // mute/unmute strategies using an incompatible device combination
7198 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7199 // if unmuting, unmute only after the specified delay
7200 if (outputDesc->isDuplicated()) {
7201 return 0;
7202 }
7203
7204 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007205 DeviceVector devices = outputDesc->devices();
7206 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007207
François Gaffiec005e562018-11-06 15:04:49 +01007208 auto productStrategies = mEngine->getOrderedProductStrategies();
7209 for (const auto &productStrategy : productStrategies) {
7210 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7211 DeviceVector curDevices =
7212 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7213 curDevices = curDevices.filter(outputDesc->supportedDevices());
7214 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007215 bool doMute = false;
7216
François Gaffiec005e562018-11-06 15:04:49 +01007217 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007218 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007219 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7220 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007221 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007222 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007223 }
Eric Laurent99401132014-05-07 19:48:15 -07007224 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007225 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007226 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007227 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007228 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007229 continue;
7230 }
François Gaffiec005e562018-11-06 15:04:49 +01007231 ALOGVV("%s() %s (curDevice %s)", __func__,
7232 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7233 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7234 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007235 if (mute) {
7236 // FIXME: should not need to double latency if volume could be applied
7237 // immediately by the audioflinger mixer. We must account for the delay
7238 // between now and the next time the audioflinger thread for this output
7239 // will process a buffer (which corresponds to one buffer size,
7240 // usually 1/2 or 1/4 of the latency).
7241 if (muteWaitMs < desc->latency() * 2) {
7242 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007243 }
7244 }
7245 }
7246 }
7247 }
7248 }
7249
Eric Laurent99401132014-05-07 19:48:15 -07007250 // temporary mute output if device selection changes to avoid volume bursts due to
7251 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007252 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007253 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007254
Eric Laurentdc462862016-07-19 12:29:53 -07007255 if (muteWaitMs < tempMuteWaitMs) {
7256 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007257 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007258
7259 // If recommended duration is defined, replace temporary mute duration to avoid
7260 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7261 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7262 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7263 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7264 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7265
François Gaffieaaac0fd2018-11-22 17:56:39 +01007266 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7267 // make sure that we do not start the temporary mute period too early in case of
7268 // delayed device change
7269 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7270 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007271 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007272 }
7273 }
7274
Eric Laurente552edb2014-03-10 17:42:56 -07007275 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7276 if (muteWaitMs > delayMs) {
7277 muteWaitMs -= delayMs;
7278 usleep(muteWaitMs * 1000);
7279 return muteWaitMs;
7280 }
7281 return 0;
7282}
7283
François Gaffie11d30102018-11-02 16:09:09 +01007284uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7285 const DeviceVector &devices,
7286 bool force,
7287 int delayMs,
7288 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02007289 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07007290{
jiabin3ff8d7d2022-12-13 06:27:44 +00007291 // TODO(b/262404095): Consider if the output need to be reopened.
François Gaffie11d30102018-11-02 16:09:09 +01007292 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007293 uint32_t muteWaitMs;
7294
7295 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01007296 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
7297 nullptr /* patchHandle */, requiresMuteCheck);
7298 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
7299 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07007300 return muteWaitMs;
7301 }
Eric Laurente552edb2014-03-10 17:42:56 -07007302
7303 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007304 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007305 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007306 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007307
François Gaffie11d30102018-11-02 16:09:09 +01007308 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7309
7310 if (!filteredDevices.isEmpty()) {
7311 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007312 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007313
7314 // if the outputs are not materially active, there is no need to mute.
7315 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007316 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007317 } else {
7318 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7319 muteWaitMs = 0;
7320 }
Eric Laurente552edb2014-03-10 17:42:56 -07007321
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007322 bool outputRouted = outputDesc->isRouted();
7323
Eric Laurent79ea9582020-06-11 18:49:24 -07007324 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7325 // output profile or if new device is not supported AND previous device(s) is(are) still
7326 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007327 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007328 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7329 // restore previous device after evaluating strategy mute state
7330 outputDesc->setDevices(prevDevices);
7331 return muteWaitMs;
7332 }
7333
Eric Laurente552edb2014-03-10 17:42:56 -07007334 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007335 // the requested device is AUDIO_DEVICE_NONE
7336 // OR the requested device is the same as current device
7337 // AND force is not specified
7338 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007339 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007340 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007341 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7342 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007343 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7344 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7345 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7346 }
Eric Laurente552edb2014-03-10 17:42:56 -07007347 return muteWaitMs;
7348 }
7349
François Gaffie11d30102018-11-02 16:09:09 +01007350 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007351
Eric Laurente552edb2014-03-10 17:42:56 -07007352 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007353 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007354 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007355 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007356 PatchBuilder patchBuilder;
7357 patchBuilder.addSource(outputDesc);
7358 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7359 for (const auto &filteredDevice : filteredDevices) {
7360 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007361 }
7362
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007363 // Add half reported latency to delayMs when muteWaitMs is null in order
7364 // to avoid disordered sequence of muting volume and changing devices.
7365 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7366 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007367 }
Eric Laurente552edb2014-03-10 17:42:56 -07007368
7369 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007370 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007371
7372 return muteWaitMs;
7373}
7374
Eric Laurentc75307b2015-03-17 15:29:32 -07007375status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007376 int delayMs,
7377 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007378{
Eric Laurent6a94d692014-05-20 11:18:06 -07007379 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007380 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7381 return INVALID_OPERATION;
7382 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007383 if (patchHandle) {
7384 index = mAudioPatches.indexOfKey(*patchHandle);
7385 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007386 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007387 }
7388 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007389 return INVALID_OPERATION;
7390 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007391 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007392 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007393 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007394 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007395 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007396 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007397 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007398 return status;
7399}
7400
7401status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007402 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007403 bool force,
7404 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007405{
7406 status_t status = NO_ERROR;
7407
Eric Laurent1f2f2232014-06-02 12:01:23 -07007408 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007409 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7410 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007411
François Gaffie11d30102018-11-02 16:09:09 +01007412 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007413 PatchBuilder patchBuilder;
7414 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007415 // AUDIO_SOURCE_HOTWORD is for internal use only:
7416 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007417 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7418 auto result = usecase;
7419 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7420 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7421 }
7422 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007423 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007424 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007425 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007426 }
7427 }
7428 return status;
7429}
7430
Eric Laurent6a94d692014-05-20 11:18:06 -07007431status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7432 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007433{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007434 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007435 ssize_t index;
7436 if (patchHandle) {
7437 index = mAudioPatches.indexOfKey(*patchHandle);
7438 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007439 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007440 }
7441 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007442 return INVALID_OPERATION;
7443 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007444 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007445 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007446 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007447 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007448 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007449 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007450 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007451 return status;
7452}
7453
François Gaffie11d30102018-11-02 16:09:09 +01007454sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007455 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007456 audio_format_t& format,
7457 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007458 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007459{
7460 // Choose an input profile based on the requested capture parameters: select the first available
7461 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007462 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007463 //
7464 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7465 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007466
Atneya Nair0f0a8032022-12-12 16:20:12 -08007467 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7468 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7469 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7470
7471 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007472
jiabin2fd710d2022-05-02 23:20:22 +00007473 for (;;) {
7474 sp<IOProfile> firstInexact = nullptr;
7475 uint32_t updatedSamplingRate = 0;
7476 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7477 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7478 for (const auto& hwModule : mHwModules) {
7479 for (const auto& profile : hwModule->getInputProfiles()) {
7480 // profile->log();
7481 //updatedFormat = format;
7482 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7483 &samplingRate /*updatedSamplingRate*/,
7484 format,
7485 &format, /*updatedFormat*/
7486 channelMask,
7487 &channelMask /*updatedChannelMask*/,
7488 // FIXME ugly cast
7489 (audio_output_flags_t) flags,
7490 true /*exactMatchRequiredForInputFlags*/)) {
7491 return profile;
7492 }
7493 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7494 samplingRate,
7495 &updatedSamplingRate,
7496 format,
7497 &updatedFormat,
7498 channelMask,
7499 &updatedChannelMask,
7500 // FIXME ugly cast
7501 (audio_output_flags_t) flags,
7502 false /*exactMatchRequiredForInputFlags*/)) {
7503 firstInexact = profile;
7504 }
7505 }
7506 }
7507
7508 if (firstInexact != nullptr) {
7509 samplingRate = updatedSamplingRate;
7510 format = updatedFormat;
7511 channelMask = updatedChannelMask;
7512 return firstInexact;
7513 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7514 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7515 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7516 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7517 flags = AUDIO_INPUT_FLAG_NONE;
7518 } else { // fail
7519 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7520 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7521 samplingRate, format, channelMask, oriFlags);
7522 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007523 }
7524 }
jiabin2fd710d2022-05-02 23:20:22 +00007525
7526 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007527}
7528
François Gaffieaaac0fd2018-11-22 17:56:39 +01007529float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7530 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007531 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007532 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007533{
jiabin9a3361e2019-10-01 09:38:30 -07007534 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007535
7536 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7537 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7538 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7539 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007540 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7541 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7542 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7543 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7544 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007545
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007546 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007547 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7548 mOutputs.isActive(ringVolumeSrc, 0)) {
7549 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007550 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007551 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007552 }
7553
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007554 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007555 if ((volumeSource != callVolumeSrc && (isInCall() ||
7556 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007557 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007558 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7559 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007560 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7561 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7562 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007563 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007564 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007565 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007566 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007567 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007568 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007569 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7570 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7571 // programmatically muted.
7572 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7573 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7574 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007575 bool exemptFromCapping =
7576 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7577 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007578 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7579 volumeSource, volumeDb);
7580 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007581 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7582 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7583 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007584 }
7585 }
Eric Laurente552edb2014-03-10 17:42:56 -07007586 // if a headset is connected, apply the following rules to ring tones and notifications
7587 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007588 // - always attenuate notifications volume by 6dB
7589 // - attenuate ring tones volume by 6dB unless music is not playing and
7590 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007591 // - if music is playing, always limit the volume to current music volume,
7592 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007593 if (!Intersection(deviceTypes,
7594 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7595 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007596 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7597 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007598 ((volumeSource == alarmVolumeSrc ||
7599 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007600 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7601 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7602 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007603 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7604 curves.canBeMuted()) {
7605
Eric Laurente552edb2014-03-10 17:42:56 -07007606 // when the phone is ringing we must consider that music could have been paused just before
7607 // by the music application and behave as if music was active if the last music track was
7608 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007609 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007610 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007611 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007612 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007613 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7614 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007615 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007616 float musicVolDb = computeVolume(musicCurves,
7617 musicVolumeSrc,
7618 musicCurves.getVolumeIndex(musicDevice),
7619 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007620 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7621 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7622 if (volumeDb > minVolDb) {
7623 volumeDb = minVolDb;
7624 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007625 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007626 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7627 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7628 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007629 // on A2DP, also ensure notification volume is not too low compared to media when
7630 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007631 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007632 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007633 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7634 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007635 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7636 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007637 }
7638 }
jiabin9a3361e2019-10-01 09:38:30 -07007639 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007640 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007641 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007642 }
7643 }
7644
François Gaffie43c73442018-11-08 08:21:55 +01007645 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007646}
7647
Eric Laurent3839bc02018-07-10 18:33:34 -07007648int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007649 VolumeSource fromVolumeSource,
7650 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007651{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007652 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007653 return srcIndex;
7654 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007655 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7656 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007657 float minSrc = (float)srcCurves.getVolumeIndexMin();
7658 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7659 float minDst = (float)dstCurves.getVolumeIndexMin();
7660 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007661
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007662 // preserve mute request or correct range
7663 if (srcIndex < minSrc) {
7664 if (srcIndex == 0) {
7665 return 0;
7666 }
7667 srcIndex = minSrc;
7668 } else if (srcIndex > maxSrc) {
7669 srcIndex = maxSrc;
7670 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007671 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7672}
7673
François Gaffieaaac0fd2018-11-22 17:56:39 +01007674status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7675 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007676 int index,
7677 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007678 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007679 int delayMs,
7680 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007681{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007682 // do not change actual attributes volume if the attributes is muted
7683 if (outputDesc->isMuted(volumeSource)) {
7684 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7685 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007686 return NO_ERROR;
7687 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007688 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7689 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7690 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7691 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007692
Eric Laurent2517af32020-11-25 15:31:27 +01007693 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007694 bool isHAUsed = isHearingAidUsedForComm();
7695
Eric Laurente552edb2014-03-10 17:42:56 -07007696 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007697 // if sco and call follow same curves, bypass forceUseForComm
7698 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007699 ((isVoiceVolSrc && isScoRequested) ||
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007700 (isBtScoVolSrc && !(isScoRequested || isHAUsed)))) {
Eric Laurent2517af32020-11-25 15:31:27 +01007701 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007702 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007703 // Do not return an error here as AudioService will always set both voice call
7704 // and bluetooth SCO volumes due to stream aliasing.
7705 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007706 }
jiabin9a3361e2019-10-01 09:38:30 -07007707 if (deviceTypes.empty()) {
7708 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007709 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007710
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007711 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7712 ALOGE("invalid volume index range");
7713 return BAD_VALUE;
7714 }
7715
jiabin9a3361e2019-10-01 09:38:30 -07007716 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7717 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007718 // Force VoIP volume to max for bluetooth SCO device except if muted
7719 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007720 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007721 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007722 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007723 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007724 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007725 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007726
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007727 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007728 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007729 // 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 +01007730 if (isVoiceVolSrc) {
7731 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007732 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007733 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007734 }
Eric Laurent18fba842016-03-31 14:41:26 -07007735 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007736 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7737 mLastVoiceVolume = voiceVolume;
7738 }
7739 }
Eric Laurente552edb2014-03-10 17:42:56 -07007740 return NO_ERROR;
7741}
7742
Eric Laurentc75307b2015-03-17 15:29:32 -07007743void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007744 const DeviceTypeSet& deviceTypes,
7745 int delayMs,
7746 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007747{
jiabincd510522020-01-22 09:40:55 -08007748 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007749 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7750 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7751 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007752 curves.getVolumeIndex(deviceTypes),
7753 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007754 }
7755}
7756
François Gaffiec005e562018-11-06 15:04:49 +01007757void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7758 bool on,
7759 const sp<AudioOutputDescriptor>& outputDesc,
7760 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007761 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007762{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007763 std::vector<VolumeSource> sourcesToMute;
7764 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7765 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7766 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007767 VolumeSource source = toVolumeSource(attributes, false);
7768 if ((source != VOLUME_SOURCE_NONE) &&
7769 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7770 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007771 sourcesToMute.push_back(source);
7772 }
Eric Laurente552edb2014-03-10 17:42:56 -07007773 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007774 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007775 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007776 }
7777
Eric Laurente552edb2014-03-10 17:42:56 -07007778}
7779
François Gaffieaaac0fd2018-11-22 17:56:39 +01007780void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7781 bool on,
7782 const sp<AudioOutputDescriptor>& outputDesc,
7783 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007784 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007785{
jiabin9a3361e2019-10-01 09:38:30 -07007786 if (deviceTypes.empty()) {
7787 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007788 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007789 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007790 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007791 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007792 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007793 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007794 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7795 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007796 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007797 }
7798 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007799 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7800 // ignored
7801 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007802 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007803 if (!outputDesc->isMuted(volumeSource)) {
7804 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007805 return;
7806 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007807 if (outputDesc->decMuteCount(volumeSource) == 0) {
7808 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007809 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007810 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007811 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007812 delayMs);
7813 }
7814 }
7815}
7816
François Gaffie53615e22015-03-19 09:24:12 +01007817bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7818{
François Gaffiec005e562018-11-06 15:04:49 +01007819 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007820 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7821 return true;
7822 }
7823
7824 // has known usage?
7825 switch (paa->usage) {
7826 case AUDIO_USAGE_UNKNOWN:
7827 case AUDIO_USAGE_MEDIA:
7828 case AUDIO_USAGE_VOICE_COMMUNICATION:
7829 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7830 case AUDIO_USAGE_ALARM:
7831 case AUDIO_USAGE_NOTIFICATION:
7832 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7833 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7834 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7835 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7836 case AUDIO_USAGE_NOTIFICATION_EVENT:
7837 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7838 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7839 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7840 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007841 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007842 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007843 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007844 case AUDIO_USAGE_EMERGENCY:
7845 case AUDIO_USAGE_SAFETY:
7846 case AUDIO_USAGE_VEHICLE_STATUS:
7847 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007848 break;
7849 default:
7850 return false;
7851 }
7852 return true;
7853}
7854
François Gaffie2110e042015-03-24 08:41:51 +01007855audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7856{
7857 return mEngine->getForceUse(usage);
7858}
7859
Eric Laurent96d1dda2022-03-14 17:14:19 +01007860bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007861 return isStateInCall(mEngine->getPhoneState());
7862}
7863
Eric Laurent96d1dda2022-03-14 17:14:19 +01007864bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007865 return is_state_in_call(state);
7866}
7867
Eric Laurentf9cccec2022-11-16 19:12:00 +01007868bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007869 audio_mode_t mode = mEngine->getPhoneState();
7870 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007871 || (mode == AUDIO_MODE_CALL_SCREEN)
7872 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007873}
7874
Eric Laurentf9cccec2022-11-16 19:12:00 +01007875bool AudioPolicyManager::isInCallOrScreening() const {
7876 audio_mode_t mode = mEngine->getPhoneState();
7877 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7878}
7879
Eric Laurentd60560a2015-04-10 11:31:20 -07007880void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7881{
7882 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007883 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007884 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007885 sourceDesc->sinkDevice()->equals(deviceDesc))
7886 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007887 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007888 }
7889 }
7890
7891 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7892 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7893 bool release = false;
7894 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7895 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7896 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7897 source->ext.device.type == deviceDesc->type()) {
7898 release = true;
7899 }
7900 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007901 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007902 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7903 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7904 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007905 sink->ext.device.type == deviceDesc->type() &&
7906 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7907 || strncmp(sink->ext.device.address, address,
7908 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007909 release = true;
7910 }
7911 }
7912 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007913 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7914 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007915 }
7916 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007917
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007918 mInputs.clearSessionRoutesForDevice(deviceDesc);
7919
Francois Gaffie716e1432019-01-14 16:58:59 +01007920 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007921}
7922
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007923void AudioPolicyManager::modifySurroundFormats(
7924 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007925 std::unordered_set<audio_format_t> enforcedSurround(
7926 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007927 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7928 for (const auto& pair : mConfig.getSurroundFormats()) {
7929 allSurround.insert(pair.first);
7930 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7931 }
Phil Burk09bc4612016-02-24 15:58:15 -08007932
7933 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7934 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007935 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007936 // This is the resulting set of formats depending on the surround mode:
7937 // 'all surround' = allSurround
7938 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7939 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7940 // 'manual surround' = mManualSurroundFormats
7941 // AUTO: formats v 'enforced surround'
7942 // ALWAYS: formats v 'all surround' v 'enforced surround'
7943 // NEVER: formats ^ 'non-surround'
7944 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007945
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007946 std::unordered_set<audio_format_t> formatSet;
7947 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7948 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007949 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007950 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007951 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007952 formatSet.insert(*formatIter);
7953 }
7954 }
7955 } else {
7956 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7957 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007958 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007959
jiabin81772902018-04-02 17:52:27 -07007960 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007961 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007962 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7963 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7964 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007965 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007966 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7967 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7968 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007969 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007970 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007971 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007972 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007973 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007974 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007975}
7976
jiabin06e4bab2019-07-29 10:13:34 -07007977void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7978 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007979 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7980 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7981
7982 // If NEVER, then remove support for channelMasks > stereo.
7983 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007984 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7985 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007986 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007987 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007988 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007989 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007990 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007991 }
7992 }
jiabin81772902018-04-02 17:52:27 -07007993 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7994 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7995 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007996 bool supports5dot1 = false;
7997 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007998 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007999 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8000 supports5dot1 = true;
8001 break;
8002 }
8003 }
8004 // If not then add 5.1 support.
8005 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008006 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008007 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008008 }
Phil Burk09bc4612016-02-24 15:58:15 -08008009 }
8010}
8011
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008012void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008013 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01008014 AudioProfileVector &profiles)
8015{
8016 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008017 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07008018
François Gaffie112b0af2015-11-19 16:13:25 +01008019 // Format MUST be checked first to update the list of AudioProfile
8020 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008021 reply = mpClientInterface->getParameters(
8022 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07008023 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008024 AudioParameter repliedParameters(reply);
8025 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008026 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01008027 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
8028 return;
8029 }
Phil Burk09bc4612016-02-24 15:58:15 -08008030 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01008031 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08008032 if (device == AUDIO_DEVICE_OUT_HDMI
8033 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008034 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07008035 }
jiabin3e277cc2019-09-10 14:27:34 -07008036 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01008037 }
François Gaffie112b0af2015-11-19 16:13:25 +01008038
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008039 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07008040 ChannelMaskSet channelMasks;
8041 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01008042 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07008043 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01008044
8045 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008046 reply = mpClientInterface->getParameters(
8047 ioHandle,
8048 requestedParameters.toString() + ";" +
8049 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01008050 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008051 AudioParameter repliedParameters(reply);
8052 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008053 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008054 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01008055 }
8056 }
8057 if (profiles.hasDynamicChannelsFor(format)) {
8058 reply = mpClientInterface->getParameters(ioHandle,
8059 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07008060 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01008061 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008062 AudioParameter repliedParameters(reply);
8063 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008064 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008065 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008066 if (device == AUDIO_DEVICE_OUT_HDMI
8067 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008068 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07008069 }
François Gaffie112b0af2015-11-19 16:13:25 +01008070 }
8071 }
jiabin3e277cc2019-09-10 14:27:34 -07008072 addDynamicAudioProfileAndSort(
8073 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01008074 }
8075}
Eric Laurentd60560a2015-04-10 11:31:20 -07008076
Mikhail Naganovdc769682018-05-04 15:34:08 -07008077status_t AudioPolicyManager::installPatch(const char *caller,
8078 audio_patch_handle_t *patchHandle,
8079 AudioIODescriptorInterface *ioDescriptor,
8080 const struct audio_patch *patch,
8081 int delayMs)
8082{
8083 ssize_t index = mAudioPatches.indexOfKey(
8084 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8085 *patchHandle : ioDescriptor->getPatchHandle());
8086 sp<AudioPatch> patchDesc;
8087 status_t status = installPatch(
8088 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8089 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008090 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008091 }
8092 return status;
8093}
8094
8095status_t AudioPolicyManager::installPatch(const char *caller,
8096 ssize_t index,
8097 audio_patch_handle_t *patchHandle,
8098 const struct audio_patch *patch,
8099 int delayMs,
8100 uid_t uid,
8101 sp<AudioPatch> *patchDescPtr)
8102{
8103 sp<AudioPatch> patchDesc;
8104 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8105 if (index >= 0) {
8106 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008107 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008108 }
8109
8110 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8111 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8112 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8113 if (status == NO_ERROR) {
8114 if (index < 0) {
8115 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008116 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008117 } else {
8118 patchDesc->mPatch = *patch;
8119 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008120 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008121 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008122 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008123 }
8124 nextAudioPortGeneration();
8125 mpClientInterface->onAudioPatchListUpdate();
8126 }
8127 if (patchDescPtr) *patchDescPtr = patchDesc;
8128 return status;
8129}
8130
jiabinbce0c1d2020-10-05 11:20:18 -07008131bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8132{
8133 const TrackClientVector activeClients = output->getActiveClients();
8134 if (activeClients.empty()) {
8135 return true;
8136 }
8137 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8138 if (index < 0) {
8139 ALOGE("%s, no audio patch found while there are active clients on output %d",
8140 __func__, output->getId());
8141 return false;
8142 }
8143 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8144 DeviceVector routedDevices;
8145 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8146 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8147 patchDesc->mPatch.sinks[i].id);
8148 if (device == nullptr) {
8149 ALOGE("%s, no audio device found with id(%d)",
8150 __func__, patchDesc->mPatch.sinks[i].id);
8151 return false;
8152 }
8153 routedDevices.add(device);
8154 }
8155 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008156 if (client->isInvalid()) {
8157 // No need to take care about invalidated clients.
8158 continue;
8159 }
jiabinbce0c1d2020-10-05 11:20:18 -07008160 sp<DeviceDescriptor> preferredDevice =
8161 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8162 if (mEngine->getOutputDevicesForAttributes(
8163 client->attributes(), preferredDevice, false) == routedDevices) {
8164 return false;
8165 }
8166 }
8167 return true;
8168}
8169
8170sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008171 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008172 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8173 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008174{
8175 for (const auto& device : devices) {
8176 // TODO: This should be checking if the profile supports the device combo.
8177 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008178 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8179 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008180 return nullptr;
8181 }
8182 }
8183 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8184 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008185 status_t status = desc->open(halConfig, mixerConfig, devices,
8186 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008187 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008188 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008189 return nullptr;
8190 }
8191
8192 // Here is where the out_set_parameters() for card & device gets called
8193 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8194 const audio_devices_t deviceType = device->type();
8195 const String8 &address = String8(device->address().c_str());
8196 if (!address.isEmpty()) {
8197 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8198 mpClientInterface->setParameters(output, String8(param));
8199 free(param);
8200 }
8201 updateAudioProfiles(device, output, profile->getAudioProfiles());
8202 if (!profile->hasValidAudioProfile()) {
8203 ALOGW("%s() missing param", __func__);
8204 desc->close();
8205 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008206 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8207 // Reopen the output with the best audio profile picked by APM when the profile supports
8208 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008209 desc->close();
8210 output = AUDIO_IO_HANDLE_NONE;
8211 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8212 profile->pickAudioProfile(
8213 config.sample_rate, config.channel_mask, config.format);
8214 config.offload_info.sample_rate = config.sample_rate;
8215 config.offload_info.channel_mask = config.channel_mask;
8216 config.offload_info.format = config.format;
8217
jiabina84c3d32022-12-02 18:59:55 +00008218 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008219 if (status != NO_ERROR) {
8220 return nullptr;
8221 }
8222 }
8223
8224 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008225
baek.kim -61c20122022-07-27 10:05:32 +00008226 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8227 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8228
jiabinbce0c1d2020-10-05 11:20:18 -07008229 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8230 sp<AudioPolicyMix> policyMix;
8231 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8232 policyMix->setOutput(desc);
8233 desc->mPolicyMix = policyMix;
8234 } else {
8235 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
8236 address.string());
8237 }
8238
baek.kim -61c20122022-07-27 10:05:32 +00008239 } else if (hasPrimaryOutput() && speaker != nullptr
8240 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008241 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8242 // no duplicated output for:
8243 // - direct outputs
8244 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008245 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008246 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8247
8248 //TODO: configure audio effect output stage here
8249
8250 // open a duplicating output thread for the new output and the primary output
8251 sp<SwAudioOutputDescriptor> dupOutputDesc =
8252 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8253 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8254 if (status == NO_ERROR) {
8255 // add duplicated output descriptor
8256 addOutput(duplicatedOutput, dupOutputDesc);
8257 } else {
8258 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8259 mPrimaryOutput->mIoHandle, output);
8260 desc->close();
8261 removeOutput(output);
8262 nextAudioPortGeneration();
8263 return nullptr;
8264 }
8265 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008266 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8267 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8268 mPrimaryOutput = desc;
8269 }
jiabinbce0c1d2020-10-05 11:20:18 -07008270 return desc;
8271}
8272
jiabinf1c73972022-04-14 16:28:52 -07008273status_t AudioPolicyManager::getDevicesForAttributes(
8274 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8275 // Devices are determined in the following precedence:
8276 //
8277 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8278 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8279 //
8280 // If no such dynamic policy then
8281 // 2) Devices containing an active client using setPreferredDevice
8282 // with same strategy as the attributes.
8283 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8284 //
8285 // If no corresponding active client with setPreferredDevice then
8286 // 3) Devices associated with the strategy determined by the attributes
8287 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8288 //
8289 // See related getOutputForAttrInt().
8290
8291 // check dynamic policies but only for primary descriptors (secondary not used for audible
8292 // audio routing, only used for duplication for playback capture)
8293 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008294 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008295 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008296 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8297 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8298 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008299 if (status != OK) {
8300 return status;
8301 }
8302
8303 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8304 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8305 // as they are unaffected by device/stream volume
8306 // (per SwAudioOutputDescriptor::isFixedVolume()).
8307 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8308 ) {
8309 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8310 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8311 devices.add(deviceDesc);
8312 } else {
8313 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8314 // which selects setPreferredDevice if active. This means forVolume call
8315 // will take an active setPreferredDevice, if such exists.
8316
8317 devices = mEngine->getOutputDevicesForAttributes(
8318 attr, nullptr /* preferredDevice */, false /* fromCache */);
8319 }
8320
8321 if (forVolume) {
8322 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8323 // for single volume control in AudioService (such relationship should exist if
8324 // SPEAKER_SAFE is present).
8325 //
8326 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8327 DeviceVector speakerSafeDevices =
8328 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8329 if (!speakerSafeDevices.isEmpty()) {
8330 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8331 devices.remove(speakerSafeDevices);
8332 }
8333 }
8334
8335 return NO_ERROR;
8336}
8337
8338status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8339 AudioProfileVector& audioProfiles,
8340 uint32_t flags,
8341 bool isInput) {
8342 for (const auto& hwModule : mHwModules) {
8343 // the MSD module checks for different conditions
8344 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8345 continue;
8346 }
8347 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8348 : hwModule->getOutputProfiles();
8349 for (const auto& profile : ioProfiles) {
8350 if (!profile->areAllDevicesSupported(devices) ||
8351 !profile->isCompatibleProfileForFlags(
8352 flags, false /*exactMatchRequiredForInputFlags*/)) {
8353 continue;
8354 }
8355 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8356 }
8357 }
8358
8359 if (!isInput) {
8360 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8361 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8362 if (msdModule != nullptr) {
8363 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8364 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8365 for (const auto &profile: msdModule->getOutputProfiles()) {
8366 if (!profile->asAudioPort()->isDirectOutput()) {
8367 continue;
8368 }
8369 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8370 }
8371 } else {
8372 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8373 }
8374 }
8375 }
8376
8377 return NO_ERROR;
8378}
8379
jiabin3ff8d7d2022-12-13 06:27:44 +00008380sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8381 const audio_config_t *config,
8382 audio_output_flags_t flags,
8383 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008384 closeOutput(outputDesc->mIoHandle);
8385 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8386 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8387 if (preferredOutput == nullptr) {
8388 ALOGE("%s failed to reopen output device=%d, caller=%s",
8389 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008390 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008391 return preferredOutput;
8392}
8393
8394void AudioPolicyManager::reopenOutputsWithDevices(
8395 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8396 for (const auto& [output, devices] : outputsToReopen) {
8397 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8398 closeOutput(output);
8399 openOutputWithProfileAndDevice(desc->mProfile, devices);
8400 }
jiabina84c3d32022-12-02 18:59:55 +00008401}
8402
jiabinc44b3462022-12-08 12:52:31 -08008403PortHandleVector AudioPolicyManager::getClientsForStream(
8404 audio_stream_type_t streamType) const {
8405 PortHandleVector clients;
8406 for (size_t i = 0; i < mOutputs.size(); ++i) {
8407 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8408 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8409 }
8410 return clients;
8411}
8412
8413void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8414 PortHandleVector clients;
8415 for (auto stream : streams) {
8416 PortHandleVector clientsForStream = getClientsForStream(stream);
8417 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8418 }
8419 mpClientInterface->invalidateTracks(clients);
8420}
8421
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008422} // namespace android