blob: e910c3de42cbf790147991228088baa047298900 [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) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00003919 ALOGV("Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01003920 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003921 return status;
3922 }
3923
3924 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003925
3926 bool forceVolumeReeval = false;
3927 // FIXME: workaround for truncated touch sounds
3928 // to be removed when the problem is handled by system UI
3929 uint32_t delayMs = 0;
3930 if (strategy == mCommunnicationStrategy) {
3931 forceVolumeReeval = true;
3932 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3933 updateInputRouting();
3934 }
3935 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003936
3937 return NO_ERROR;
3938}
3939
jiabin0a488932020-08-07 17:32:40 -07003940status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3941 device_role_t role,
3942 AudioDeviceTypeAddrVector &devices) {
3943 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003944}
3945
Jiabin Huang3b98d322020-09-03 17:54:16 +00003946status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3947 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3948 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3949 dumpAudioDeviceTypeAddrVector(devices).c_str());
3950
Mikhail Naganov55773032020-10-01 15:08:13 -07003951 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003952 return BAD_VALUE;
3953 }
3954 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3955 ALOGW_IF(status != NO_ERROR,
3956 "Engine could not set preferred devices %s for audio source %d role %d",
3957 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3958
3959 return status;
3960}
3961
3962status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3963 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3964 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3965 dumpAudioDeviceTypeAddrVector(devices).c_str());
3966
Mikhail Naganov55773032020-10-01 15:08:13 -07003967 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003968 return BAD_VALUE;
3969 }
3970 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3971 ALOGW_IF(status != NO_ERROR,
3972 "Engine could not add preferred devices %s for audio source %d role %d",
3973 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3974
Eric Laurent2517af32020-11-25 15:31:27 +01003975 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003976 return status;
3977}
3978
3979status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3980 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3981{
3982 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3983 dumpAudioDeviceTypeAddrVector(devices).c_str());
3984
Mikhail Naganov55773032020-10-01 15:08:13 -07003985 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003986 return BAD_VALUE;
3987 }
3988
3989 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3990 audioSource, role, devices);
3991 ALOGW_IF(status != NO_ERROR,
3992 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3993
Eric Laurent2517af32020-11-25 15:31:27 +01003994 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003995 return status;
3996}
3997
3998status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3999 device_role_t role) {
4000 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4001
4002 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
4003 ALOGW_IF(status != NO_ERROR,
4004 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
4005
Eric Laurent2517af32020-11-25 15:31:27 +01004006 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004007 return status;
4008}
4009
4010status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4011 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4012 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4013}
4014
Oscar Azucena90e77632019-11-27 17:12:28 -08004015status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004016 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004017 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004018 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4019 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004020 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004021 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4022 if (status != NO_ERROR) {
4023 ALOGE("%s() could not set device affinity for userId %d",
4024 __FUNCTION__, userId);
4025 return status;
4026 }
4027
4028 // reevaluate outputs for all devices
4029 checkForDeviceAndOutputChanges();
4030 updateCallAndOutputRouting();
4031
4032 return NO_ERROR;
4033}
4034
4035status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004036 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08004037 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4038 if (status != NO_ERROR) {
4039 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4040 __FUNCTION__, userId);
4041 return status;
4042 }
4043
4044 // reevaluate outputs for all devices
4045 checkForDeviceAndOutputChanges();
4046 updateCallAndOutputRouting();
4047
4048 return NO_ERROR;
4049}
4050
Andy Hungc29d82b2018-10-05 12:23:17 -07004051void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004052{
Andy Hungc29d82b2018-10-05 12:23:17 -07004053 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004054 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004055 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004056 std::string stateLiteral;
4057 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004058 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004059 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4060 "communications", "media", "record", "dock", "system",
4061 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4062 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4063 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004064 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4065 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4066 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4067 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4068 dst->append(" (MANUAL: ");
4069 dumpManualSurroundFormats(dst);
4070 dst->append(")");
4071 }
4072 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004073 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004074 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4075 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004076 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07004077 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01004078
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004079 dst->append("\n");
4080 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4081 dst->append("\n");
4082 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004083 mHwModulesAll.dump(dst);
4084 mOutputs.dump(dst);
4085 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004086 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004087 mAudioPatches.dump(dst);
4088 mPolicyMixes.dump(dst);
4089 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004090
Kevin Rocardb99cc752019-03-21 20:52:24 -07004091 dst->appendFormat(" AllowedCapturePolicies:\n");
4092 for (auto& policy : mAllowedCapturePolicies) {
4093 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4094 }
4095
jiabina84c3d32022-12-02 18:59:55 +00004096 dst->appendFormat(" Preferred mixer audio configuration:\n");
4097 for (const auto it : mPreferredMixerAttrInfos) {
4098 dst->appendFormat(" - device port id: %d\n", it.first);
4099 for (const auto preferredMixerInfoIt : it.second) {
4100 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4101 preferredMixerInfoIt.second->dump(dst);
4102 }
4103 }
4104
François Gaffiec005e562018-11-06 15:04:49 +01004105 dst->appendFormat("\nPolicy Engine dump:\n");
4106 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004107}
4108
4109status_t AudioPolicyManager::dump(int fd)
4110{
4111 String8 result;
4112 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07004113 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004114 return NO_ERROR;
4115}
4116
Kevin Rocardb99cc752019-03-21 20:52:24 -07004117status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4118{
4119 mAllowedCapturePolicies[uid] = capturePolicy;
4120 return NO_ERROR;
4121}
4122
Eric Laurente552edb2014-03-10 17:42:56 -07004123// This function checks for the parameters which can be offloaded.
4124// This can be enhanced depending on the capability of the DSP and policy
4125// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004126audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004127{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004128 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004129 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004130 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004131 offloadInfo.format,
4132 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4133 offloadInfo.has_video);
4134
jiabin2b9d5a12021-12-10 01:06:29 +00004135 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004136 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004137 }
4138
4139 // See if there is a profile to support this.
4140 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004141 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004142 offloadInfo.sample_rate,
4143 offloadInfo.format,
4144 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004145 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4146 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004147 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4148 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4149 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004150 if (profile == nullptr) {
4151 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4152 }
4153 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4154 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4155 }
4156 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004157}
4158
Michael Chana94fbb22018-04-24 14:31:19 +10004159bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4160 const audio_attributes_t& attributes) {
4161 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004162 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004163 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4164 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004165 config.sample_rate,
4166 config.format,
4167 config.channel_mask,
4168 output_flags,
4169 true /* directOnly */);
4170 ALOGV("%s() profile %sfound with name: %s, "
4171 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4172 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004173 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004174 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004175
4176 // also try the MSD module if compatible profile not found
4177 if (profile == nullptr) {
4178 profile = getMsdProfileForOutput(outputDevices,
4179 config.sample_rate,
4180 config.format,
4181 config.channel_mask,
4182 output_flags,
4183 true /* directOnly */);
4184 ALOGV("%s() MSD profile %sfound with name: %s, "
4185 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4186 __FUNCTION__, profile != 0 ? "" : "NOT ",
4187 (profile != 0 ? profile->getTagName().c_str() : "null"),
4188 config.sample_rate, config.format, config.channel_mask, output_flags);
4189 }
4190 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004191}
4192
jiabin2b9d5a12021-12-10 01:06:29 +00004193bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4194 bool durationIgnored) {
4195 if (mMasterMono) {
4196 return false; // no offloading if mono is set.
4197 }
4198
4199 // Check if offload has been disabled
4200 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4201 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4202 return false;
4203 }
4204
4205 // Check if stream type is music, then only allow offload as of now.
4206 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4207 {
4208 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4209 return false;
4210 }
4211
4212 //TODO: enable audio offloading with video when ready
4213 const bool allowOffloadWithVideo =
4214 property_get_bool("audio.offload.video", false /* default_value */);
4215 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4216 ALOGV("%s: has_video == true, returning false", __func__);
4217 return false;
4218 }
4219
4220 //If duration is less than minimum value defined in property, return false
4221 const int min_duration_secs = property_get_int32(
4222 "audio.offload.min.duration.secs", -1 /* default_value */);
4223 if (!durationIgnored) {
4224 if (min_duration_secs >= 0) {
4225 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4226 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4227 __func__, min_duration_secs);
4228 return false;
4229 }
4230 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4231 ALOGV("%s: Offload denied by duration < default min(=%u)",
4232 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4233 return false;
4234 }
4235 }
4236
4237 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4238 // creating an offloaded track and tearing it down immediately after start when audioflinger
4239 // detects there is an active non offloadable effect.
4240 // FIXME: We should check the audio session here but we do not have it in this context.
4241 // This may prevent offloading in rare situations where effects are left active by apps
4242 // in the background.
4243 if (mEffects.isNonOffloadableEffectEnabled()) {
4244 return false;
4245 }
4246
4247 return true;
4248}
4249
4250audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4251 const audio_config_t *config) {
4252 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4253 offloadInfo.format = config->format;
4254 offloadInfo.sample_rate = config->sample_rate;
4255 offloadInfo.channel_mask = config->channel_mask;
4256 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4257 offloadInfo.has_video = false;
4258 offloadInfo.is_streaming = false;
4259 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4260
4261 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4262 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4263 audio_flags_to_audio_output_flags(attr->flags, &flags);
4264 // only retain flags that will drive compressed offload or passthrough
4265 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4266 if (offloadPossible) {
4267 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4268 }
4269 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4270
Dorin Drimusfae3c642022-03-17 18:36:30 +01004271 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004272 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004273 DeviceVector outputDevices = engineOutputDevices;
4274 // the MSD module checks for different conditions and output devices
4275 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4276 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4277 continue;
4278 }
4279 outputDevices = getMsdAudioOutDevices();
4280 }
jiabin2b9d5a12021-12-10 01:06:29 +00004281 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004282 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004283 config->sample_rate, nullptr /*updatedSamplingRate*/,
4284 config->format, nullptr /*updatedFormat*/,
4285 config->channel_mask, nullptr /*updatedChannelMask*/,
4286 flags)) {
4287 continue;
4288 }
4289 // reject profiles not corresponding to a device currently available
4290 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4291 continue;
4292 }
4293 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4294 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004295 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004296 != AUDIO_DIRECT_NOT_SUPPORTED) {
4297 // Already reports offload gapless supported. No need to report offload support.
4298 continue;
4299 }
4300 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4301 != AUDIO_OUTPUT_FLAG_NONE) {
4302 // If offload gapless is reported, no need to report offload support.
4303 directMode = (audio_direct_mode_t) ((directMode &
4304 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4305 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4306 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004307 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004308 }
4309 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004310 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004311 }
4312 }
4313 }
4314 return directMode;
4315}
4316
Dorin Drimusf2196d82022-01-03 12:11:18 +01004317status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4318 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004319 if (mEffects.isNonOffloadableEffectEnabled()) {
4320 return OK;
4321 }
jiabinf1c73972022-04-14 16:28:52 -07004322 DeviceVector devices;
4323 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004324 if (status != OK) {
4325 return status;
4326 }
4327 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4328 if (devices.empty()) {
4329 return OK; // no output devices for the attributes
4330 }
jiabinf1c73972022-04-14 16:28:52 -07004331 return getProfilesForDevices(devices, audioProfilesVector,
4332 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004333}
4334
jiabina84c3d32022-12-02 18:59:55 +00004335status_t AudioPolicyManager::getSupportedMixerAttributes(
4336 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4337 ALOGV("%s, portId=%d", __func__, portId);
4338 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4339 if (deviceDescriptor == nullptr) {
4340 ALOGE("%s the requested device is currently unavailable", __func__);
4341 return BAD_VALUE;
4342 }
4343 for (const auto& hwModule : mHwModules) {
4344 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4345 if (curProfile->supportsDevice(deviceDescriptor)) {
4346 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4347 }
4348 }
4349 }
4350 return NO_ERROR;
4351}
4352
4353status_t AudioPolicyManager::setPreferredMixerAttributes(
4354 const audio_attributes_t *attr,
4355 audio_port_handle_t portId,
4356 uid_t uid,
4357 const audio_mixer_attributes_t *mixerAttributes) {
4358 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4359 "mixerBehavior=%d}, uid=%d, portId=%u",
4360 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4361 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4362 mixerAttributes->mixer_behavior, uid, portId);
4363 if (attr->usage != AUDIO_USAGE_MEDIA) {
4364 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4365 return BAD_VALUE;
4366 }
4367 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4368 if (deviceDescriptor == nullptr) {
4369 ALOGE("%s the requested device is currently unavailable", __func__);
4370 return BAD_VALUE;
4371 }
4372 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4373 ALOGE("%s(%d), type=%d, is not a usb output device",
4374 __func__, portId, deviceDescriptor->type());
4375 return BAD_VALUE;
4376 }
4377
4378 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4379 audio_flags_to_audio_output_flags(attr->flags, &flags);
4380 flags = (audio_output_flags_t) (flags |
4381 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4382 sp<IOProfile> profile = nullptr;
4383 DeviceVector devices(deviceDescriptor);
4384 for (const auto& hwModule : mHwModules) {
4385 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4386 if (curProfile->hasDynamicAudioProfile()
4387 && curProfile->isCompatibleProfile(devices,
4388 mixerAttributes->config.sample_rate,
4389 nullptr /*updatedSamplingRate*/,
4390 mixerAttributes->config.format,
4391 nullptr /*updatedFormat*/,
4392 mixerAttributes->config.channel_mask,
4393 nullptr /*updatedChannelMask*/,
4394 flags,
4395 false /*exactMatchRequiredForInputFlags*/)) {
4396 profile = curProfile;
4397 break;
4398 }
4399 }
4400 }
4401 if (profile == nullptr) {
4402 ALOGE("%s, there is no compatible profile found", __func__);
4403 return BAD_VALUE;
4404 }
4405
4406 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4407 sp<PreferredMixerAttributesInfo>::make(
4408 uid, portId, profile, flags, *mixerAttributes);
4409 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4410 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4411
4412 // If 1) there is any client from the preferred mixer configuration owner that is currently
4413 // active and matches the strategy and 2) current output is on the preferred device and the
4414 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4415 // configuration.
4416 std::vector<audio_io_handle_t> outputsToReopen;
4417 for (size_t i = 0; i < mOutputs.size(); i++) {
4418 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004419 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4420 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4421 output->mUsePreferredMixerAttributes = true;
4422 } else {
4423 for (const auto &client: output->getActiveClients()) {
4424 if (client->uid() == uid && client->strategy() == strategy) {
4425 client->setIsInvalid();
4426 outputsToReopen.push_back(output->mIoHandle);
4427 }
jiabina84c3d32022-12-02 18:59:55 +00004428 }
4429 }
4430 }
4431 }
4432 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4433 config.sample_rate = mixerAttributes->config.sample_rate;
4434 config.channel_mask = mixerAttributes->config.channel_mask;
4435 config.format = mixerAttributes->config.format;
4436 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004437 sp<SwAudioOutputDescriptor> desc =
4438 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4439 if (desc == nullptr) {
4440 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4441 continue;
4442 }
4443 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004444 }
4445
4446 return NO_ERROR;
4447}
4448
4449sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
4450 audio_port_handle_t devicePortId, product_strategy_t strategy) {
4451 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4452 if (it == mPreferredMixerAttrInfos.end()) {
4453 return nullptr;
4454 }
4455 auto mixerAttrInfoIt = it->second.find(strategy);
4456 if (mixerAttrInfoIt == it->second.end()) {
4457 return nullptr;
4458 }
4459 return mixerAttrInfoIt->second;
4460}
4461
4462status_t AudioPolicyManager::getPreferredMixerAttributes(
4463 const audio_attributes_t *attr,
4464 audio_port_handle_t portId,
4465 audio_mixer_attributes_t* mixerAttributes) {
4466 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4467 portId, mEngine->getProductStrategyForAttributes(*attr));
4468 if (info == nullptr) {
4469 return NAME_NOT_FOUND;
4470 }
4471 *mixerAttributes = info->getMixerAttributes();
4472 return NO_ERROR;
4473}
4474
4475status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4476 audio_port_handle_t portId,
4477 uid_t uid) {
4478 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4479 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4480 if (preferredMixerAttrInfo == nullptr) {
4481 return NAME_NOT_FOUND;
4482 }
4483 if (preferredMixerAttrInfo->getUid() != uid) {
4484 ALOGE("%s, requested uid=%d, owned uid=%d",
4485 __func__, uid, preferredMixerAttrInfo->getUid());
4486 return PERMISSION_DENIED;
4487 }
4488 mPreferredMixerAttrInfos[portId].erase(strategy);
4489 if (mPreferredMixerAttrInfos[portId].empty()) {
4490 mPreferredMixerAttrInfos.erase(portId);
4491 }
4492
4493 // Reconfig existing output
4494 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4495 for (size_t i = 0; i < mOutputs.size(); i++) {
4496 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4497 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4498 }
4499 }
4500 for (const auto output : potentialOutputsToReopen) {
4501 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4502 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4503 preferredMixerAttrInfo->getFlags())) {
4504 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4505 }
4506 }
4507 return NO_ERROR;
4508}
4509
Eric Laurent6a94d692014-05-20 11:18:06 -07004510status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4511 audio_port_type_t type,
4512 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004513 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004514 unsigned int *generation)
4515{
jiabin19cdba52020-11-24 11:28:58 -08004516 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4517 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004518 return BAD_VALUE;
4519 }
4520 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004521 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004522 *num_ports = 0;
4523 }
4524
4525 size_t portsWritten = 0;
4526 size_t portsMax = *num_ports;
4527 *num_ports = 0;
4528 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004529 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4530 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004531 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004532 for (const auto& dev : mAvailableOutputDevices) {
4533 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004534 continue;
4535 }
4536 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004537 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004538 }
4539 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004540 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004541 }
4542 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004543 for (const auto& dev : mAvailableInputDevices) {
4544 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004545 continue;
4546 }
4547 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004548 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004549 }
4550 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004551 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004552 }
4553 }
4554 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4555 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4556 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4557 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4558 }
4559 *num_ports += mInputs.size();
4560 }
4561 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004562 size_t numOutputs = 0;
4563 for (size_t i = 0; i < mOutputs.size(); i++) {
4564 if (!mOutputs[i]->isDuplicated()) {
4565 numOutputs++;
4566 if (portsWritten < portsMax) {
4567 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4568 }
4569 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004570 }
Eric Laurent84c70242014-06-23 08:46:27 -07004571 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004572 }
4573 }
jiabina84c3d32022-12-02 18:59:55 +00004574
Eric Laurent6a94d692014-05-20 11:18:06 -07004575 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004576 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004577 return NO_ERROR;
4578}
4579
jiabin19cdba52020-11-24 11:28:58 -08004580status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004581{
Eric Laurent99fcae42018-05-17 16:59:18 -07004582 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4583 return BAD_VALUE;
4584 }
4585 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4586 if (dev != 0) {
4587 dev->toAudioPort(port);
4588 return NO_ERROR;
4589 }
4590 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4591 if (dev != 0) {
4592 dev->toAudioPort(port);
4593 return NO_ERROR;
4594 }
4595 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4596 if (out != 0) {
4597 out->toAudioPort(port);
4598 return NO_ERROR;
4599 }
4600 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4601 if (in != 0) {
4602 in->toAudioPort(port);
4603 return NO_ERROR;
4604 }
4605 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004606}
4607
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004608status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4609 audio_patch_handle_t *handle,
4610 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004611{
François Gaffieafd4cea2019-11-18 15:50:22 +01004612 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004613 if (handle == NULL || patch == NULL) {
4614 return BAD_VALUE;
4615 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004616 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004617 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004618 return BAD_VALUE;
4619 }
4620 // only one source per audio patch supported for now
4621 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004622 return INVALID_OPERATION;
4623 }
Eric Laurent874c42872014-08-08 15:13:39 -07004624 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004625 return INVALID_OPERATION;
4626 }
Eric Laurent874c42872014-08-08 15:13:39 -07004627 for (size_t i = 0; i < patch->num_sinks; i++) {
4628 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4629 return INVALID_OPERATION;
4630 }
4631 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004632
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004633 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4634 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4635 if (srcDevice == nullptr || sinkDevice == nullptr) {
4636 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4637 return BAD_VALUE;
4638 }
4639 ALOGV("%s between source %s and sink %s", __func__,
4640 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4641 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4642 // Default attributes, default volume priority, not to infer with non raw audio patches.
4643 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4644 const struct audio_port_config *source = &patch->sources[0];
4645 sp<SourceClientDescriptor> sourceDesc =
4646 new InternalSourceClientDescriptor(
4647 portId, uid, attributes, *source, srcDevice, sinkDevice,
4648 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4649
4650 status_t status =
4651 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4652
4653 if (status != NO_ERROR) {
4654 return INVALID_OPERATION;
4655 }
4656 mAudioSources.add(portId, sourceDesc);
4657 return NO_ERROR;
4658}
4659
4660status_t AudioPolicyManager::connectAudioSourceToSink(
4661 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4662 const struct audio_patch *patch,
4663 audio_patch_handle_t &handle,
4664 uid_t uid, uint32_t delayMs)
4665{
4666 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4667 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4668 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4669 return INVALID_OPERATION;
4670 }
4671 sourceDesc->connect(handle, sinkDevice);
4672 if (isMsdPatch(handle)) {
4673 return NO_ERROR;
4674 }
4675 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4676 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4677 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4678 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4679 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4680 goto FailurePatchAdded;
4681 }
4682 status = swOutput->start();
4683 if (status != NO_ERROR) {
4684 goto FailureSourceAdded;
4685 }
4686 swOutput->addClient(sourceDesc);
4687 status = startSource(swOutput, sourceDesc, &delayMs);
4688 if (status != NO_ERROR) {
4689 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4690 goto FailureSourceActive;
4691 }
4692 if (delayMs != 0) {
4693 usleep(delayMs * 1000);
4694 }
4695 return NO_ERROR;
4696
4697FailureSourceActive:
4698 swOutput->stop();
4699 releaseOutput(sourceDesc->portId());
4700FailureSourceAdded:
4701 sourceDesc->setSwOutput(nullptr);
4702FailurePatchAdded:
4703 releaseAudioPatchInternal(handle);
4704 return INVALID_OPERATION;
4705}
4706
4707status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4708 audio_patch_handle_t *handle,
4709 uid_t uid, uint32_t delayMs,
4710 const sp<SourceClientDescriptor>& sourceDesc)
4711{
4712 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004713 sp<AudioPatch> patchDesc;
4714 ssize_t index = mAudioPatches.indexOfKey(*handle);
4715
François Gaffieafd4cea2019-11-18 15:50:22 +01004716 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4717 patch->sources[0].role,
4718 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004719#if LOG_NDEBUG == 0
4720 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004721 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4722 patch->sinks[i].role,
4723 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004724 }
4725#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004726
4727 if (index >= 0) {
4728 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004729 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4730 __func__, mUidCached, patchDesc->getUid(), uid);
4731 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004732 return INVALID_OPERATION;
4733 }
4734 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004735 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004736 }
4737
4738 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004739 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004740 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004741 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004742 return BAD_VALUE;
4743 }
Eric Laurent84c70242014-06-23 08:46:27 -07004744 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4745 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004746 if (patchDesc != 0) {
4747 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004748 ALOGV("%s source id differs for patch current id %d new id %d",
4749 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004750 return BAD_VALUE;
4751 }
4752 }
Eric Laurent874c42872014-08-08 15:13:39 -07004753 DeviceVector devices;
4754 for (size_t i = 0; i < patch->num_sinks; i++) {
4755 // Only support mix to devices connection
4756 // TODO add support for mix to mix connection
4757 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004758 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004759 return INVALID_OPERATION;
4760 }
4761 sp<DeviceDescriptor> devDesc =
4762 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4763 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004764 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004765 return BAD_VALUE;
4766 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004767
François Gaffie11d30102018-11-02 16:09:09 +01004768 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004769 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004770 NULL, // updatedSamplingRate
4771 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004772 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004773 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004774 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004775 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004776 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004777 return INVALID_OPERATION;
4778 }
4779 devices.add(devDesc);
4780 }
4781 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004782 return INVALID_OPERATION;
4783 }
Eric Laurent874c42872014-08-08 15:13:39 -07004784
Eric Laurent6a94d692014-05-20 11:18:06 -07004785 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004786 ALOGV("%s setting device %s on output %d",
4787 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004788 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004789 index = mAudioPatches.indexOfKey(*handle);
4790 if (index >= 0) {
4791 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004792 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004793 }
4794 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004795 patchDesc->setUid(uid);
4796 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004797 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004798 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004799 return INVALID_OPERATION;
4800 }
4801 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4802 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4803 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004804 // only one sink supported when connecting an input device to a mix
4805 if (patch->num_sinks > 1) {
4806 return INVALID_OPERATION;
4807 }
François Gaffie53615e22015-03-19 09:24:12 +01004808 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004809 if (inputDesc == NULL) {
4810 return BAD_VALUE;
4811 }
4812 if (patchDesc != 0) {
4813 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4814 return BAD_VALUE;
4815 }
4816 }
François Gaffie11d30102018-11-02 16:09:09 +01004817 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004818 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004819 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004820 return BAD_VALUE;
4821 }
4822
François Gaffie11d30102018-11-02 16:09:09 +01004823 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004824 patch->sinks[0].sample_rate,
4825 NULL, /*updatedSampleRate*/
4826 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004827 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004828 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004829 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004830 // FIXME for the parameter type,
4831 // and the NONE
4832 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004833 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004834 return INVALID_OPERATION;
4835 }
4836 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004837 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004838 device->toString().c_str(), inputDesc->mIoHandle);
4839 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004840 index = mAudioPatches.indexOfKey(*handle);
4841 if (index >= 0) {
4842 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004843 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004844 }
4845 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004846 patchDesc->setUid(uid);
4847 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004848 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004849 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004850 return INVALID_OPERATION;
4851 }
4852 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4853 // device to device connection
4854 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004855 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004856 return BAD_VALUE;
4857 }
4858 }
François Gaffie11d30102018-11-02 16:09:09 +01004859 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004860 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004861 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004862 return BAD_VALUE;
4863 }
Eric Laurent874c42872014-08-08 15:13:39 -07004864
Eric Laurent6a94d692014-05-20 11:18:06 -07004865 //update source and sink with our own data as the data passed in the patch may
4866 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004867 PatchBuilder patchBuilder;
4868 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004869
4870 // if first sink is to MSD, establish single MSD patch
4871 if (getMsdAudioOutDevices().contains(
4872 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4873 ALOGV("%s patching to MSD", __FUNCTION__);
4874 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4875 goto installPatch;
4876 }
4877
François Gaffieafd4cea2019-11-18 15:50:22 +01004878 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4879 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004880
Eric Laurent874c42872014-08-08 15:13:39 -07004881 for (size_t i = 0; i < patch->num_sinks; i++) {
4882 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004883 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004884 return INVALID_OPERATION;
4885 }
François Gaffie11d30102018-11-02 16:09:09 +01004886 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004887 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004888 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004889 return BAD_VALUE;
4890 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004891 audio_port_config sinkPortConfig = {};
4892 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4893 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004894
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004895 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4896 // volume management purpose (tracking activity)
4897 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4898 // in config XML to reach the sink so that is can be declared as available.
4899 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004900 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004901 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004902 // take care of dynamic routing for SwOutput selection,
4903 audio_attributes_t attributes = sourceDesc->attributes();
4904 audio_stream_type_t stream = sourceDesc->stream();
4905 audio_attributes_t resultAttr;
4906 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4907 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02004908 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
4909 config.channel_mask =
4910 (audio_channel_mask_get_representation(sourceMask)
4911 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
4912 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004913 config.format = sourceDesc->config().format;
4914 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4915 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4916 bool isRequestedDeviceForExclusiveUse = false;
4917 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004918 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00004919 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004920 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4921 &stream, sourceDesc->uid(), &config, &flags,
4922 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00004923 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004924 if (output == AUDIO_IO_HANDLE_NONE) {
4925 ALOGV("%s no output for device %s",
4926 __FUNCTION__, sinkDevice->toString().c_str());
4927 return INVALID_OPERATION;
4928 }
4929 outputDesc = mOutputs.valueFor(output);
4930 if (outputDesc->isDuplicated()) {
4931 ALOGE("%s output is duplicated", __func__);
4932 return INVALID_OPERATION;
4933 }
François Gaffie7e39df22022-04-26 12:48:49 +02004934 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4935 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004936 } else {
4937 // Same for "raw patches" aka created from createAudioPatch API
4938 SortedVector<audio_io_handle_t> outputs =
4939 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4940 // if the sink device is reachable via an opened output stream, request to
4941 // go via this output stream by adding a second source to the patch
4942 // description
4943 output = selectOutput(outputs);
4944 if (output == AUDIO_IO_HANDLE_NONE) {
4945 ALOGE("%s no output available for internal patch sink", __func__);
4946 return INVALID_OPERATION;
4947 }
4948 outputDesc = mOutputs.valueFor(output);
4949 if (outputDesc->isDuplicated()) {
4950 ALOGV("%s output for device %s is duplicated",
4951 __func__, sinkDevice->toString().c_str());
4952 return INVALID_OPERATION;
4953 }
François Gaffie7e39df22022-04-26 12:48:49 +02004954 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004955 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004956 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004957 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004958 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004959 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004960 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4961 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004962 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4963 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004964 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004965 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004966 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004967 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004968 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004969 return INVALID_OPERATION;
4970 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004971 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004972 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004973 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004974 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004975 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02004976 srcMixPortConfig.ext.mix.usecase.stream =
4977 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004978 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4979 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004980 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004981 }
Eric Laurent83b88082014-06-20 18:31:16 -07004982 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004983 }
4984 // TODO: check from routing capabilities in config file and other conflicting patches
4985
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004986installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004987 status_t status = installPatch(
4988 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004989 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004990 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004991 return INVALID_OPERATION;
4992 }
4993 } else {
4994 return BAD_VALUE;
4995 }
4996 } else {
4997 return BAD_VALUE;
4998 }
4999 return NO_ERROR;
5000}
5001
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005002status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005003{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005004 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005005 ssize_t index = mAudioPatches.indexOfKey(handle);
5006
5007 if (index < 0) {
5008 return BAD_VALUE;
5009 }
5010 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005011 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5012 __func__, mUidCached, patchDesc->getUid(), uid);
5013 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005014 return INVALID_OPERATION;
5015 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005016 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5017 for (size_t i = 0; i < mAudioSources.size(); i++) {
5018 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5019 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5020 portId = sourceDesc->portId();
5021 break;
5022 }
5023 }
5024 return portId != AUDIO_PORT_HANDLE_NONE ?
5025 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005026}
Eric Laurent6a94d692014-05-20 11:18:06 -07005027
François Gaffieafd4cea2019-11-18 15:50:22 +01005028status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005029 uint32_t delayMs,
5030 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005031{
5032 ALOGV("%s patch %d", __func__, handle);
5033 if (mAudioPatches.indexOfKey(handle) < 0) {
5034 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5035 return BAD_VALUE;
5036 }
5037 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005038 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005039 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005040 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005041 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005042 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005043 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005044 return BAD_VALUE;
5045 }
5046
François Gaffie11d30102018-11-02 16:09:09 +01005047 setOutputDevices(outputDesc,
5048 getNewOutputDevices(outputDesc, true /*fromCache*/),
5049 true,
5050 0,
5051 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005052 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5053 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005054 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005055 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005056 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005057 return BAD_VALUE;
5058 }
5059 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005060 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005061 true,
5062 NULL);
5063 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005064 status_t status =
5065 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5066 ALOGV("%s patch panel returned %d patchHandle %d",
5067 __func__, status, patchDesc->getAfHandle());
5068 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005069 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005070 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005071 // SW or HW Bridge
5072 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5073 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005074 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005075 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5076 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5077 outputDesc = sourceDesc->swOutput().promote();
5078 }
5079 if (outputDesc == nullptr) {
5080 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5081 // releaseOutput has already called closeOutput in case of direct output
5082 return NO_ERROR;
5083 }
François Gaffie7e39df22022-04-26 12:48:49 +02005084 patchHandle = outputDesc->getPatchHandle();
5085 // When a Sw bridge is released, the mixer used by this bridge will release its
5086 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
5087 // Reuse patch handle to force audio flinger removing initial mixer patch removal
5088 // updating hal patch handle (prevent leaks).
5089 // While using a HwBridge, force reconsidering device only if not reusing an existing
5090 // output and no more activity on output (will force to close).
5091 bool force = sourceDesc->useSwBridge() ||
5092 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
5093 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5094 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5095 // Reconsider device only for cases:
5096 // 1 / Active Output
5097 // 2 / Inactive Output previously hosting HwBridge
5098 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5099 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5100 sourceDesc->canCloseOutput();
5101 setOutputDevices(outputDesc,
5102 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5103 outputDesc->devices(),
5104 force,
5105 0,
5106 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005107 } else {
5108 return BAD_VALUE;
5109 }
5110 } else {
5111 return BAD_VALUE;
5112 }
5113 return NO_ERROR;
5114}
5115
5116status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5117 struct audio_patch *patches,
5118 unsigned int *generation)
5119{
François Gaffie53615e22015-03-19 09:24:12 +01005120 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005121 return BAD_VALUE;
5122 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005123 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005124 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005125}
5126
Eric Laurente1715a42014-05-20 11:30:42 -07005127status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005128{
Eric Laurente1715a42014-05-20 11:30:42 -07005129 ALOGV("setAudioPortConfig()");
5130
5131 if (config == NULL) {
5132 return BAD_VALUE;
5133 }
5134 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5135 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005136 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5137 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005138 }
5139
Eric Laurenta121f902014-06-03 13:32:54 -07005140 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005141 if (config->type == AUDIO_PORT_TYPE_MIX) {
5142 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005143 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005144 if (outputDesc == NULL) {
5145 return BAD_VALUE;
5146 }
Eric Laurent84c70242014-06-23 08:46:27 -07005147 ALOG_ASSERT(!outputDesc->isDuplicated(),
5148 "setAudioPortConfig() called on duplicated output %d",
5149 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005150 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005151 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005152 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005153 if (inputDesc == NULL) {
5154 return BAD_VALUE;
5155 }
Eric Laurenta121f902014-06-03 13:32:54 -07005156 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005157 } else {
5158 return BAD_VALUE;
5159 }
5160 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5161 sp<DeviceDescriptor> deviceDesc;
5162 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5163 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5164 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5165 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5166 } else {
5167 return BAD_VALUE;
5168 }
5169 if (deviceDesc == NULL) {
5170 return BAD_VALUE;
5171 }
Eric Laurenta121f902014-06-03 13:32:54 -07005172 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005173 } else {
5174 return BAD_VALUE;
5175 }
5176
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005177 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005178 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5179 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005180 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005181 audioPortConfig->toAudioPortConfig(&newConfig, config);
5182 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005183 }
Eric Laurenta121f902014-06-03 13:32:54 -07005184 if (status != NO_ERROR) {
5185 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005186 }
Eric Laurente1715a42014-05-20 11:30:42 -07005187
5188 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005189}
5190
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005191void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5192{
Eric Laurentd60560a2015-04-10 11:31:20 -07005193 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005194 clearAudioPatches(uid);
5195 clearSessionRoutes(uid);
5196}
5197
Eric Laurent6a94d692014-05-20 11:18:06 -07005198void AudioPolicyManager::clearAudioPatches(uid_t uid)
5199{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005200 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005201 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005202 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005203 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005204 }
5205 }
5206}
5207
François Gaffiec005e562018-11-06 15:04:49 +01005208void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005209{
François Gaffiec005e562018-11-06 15:04:49 +01005210 // Take the first attributes following the product strategy as it is used to retrieve the routed
5211 // device. All attributes wihin a strategy follows the same "routing strategy"
5212 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5213 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005214 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005215 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005216 for (size_t j = 0; j < mOutputs.size(); j++) {
5217 if (mOutputs.keyAt(j) == ouptutToSkip) {
5218 continue;
5219 }
5220 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005221 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005222 continue;
5223 }
5224 // If the default device for this strategy is on another output mix,
5225 // invalidate all tracks in this strategy to force re connection.
5226 // Otherwise select new device on the output mix.
5227 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005228 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005229 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005230 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5231 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5232 // If the device is using preferred mixer attributes, the output need to reopen
5233 // with default configuration when the new selected devices are different from
5234 // current routing devices.
5235 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5236 continue;
5237 }
5238 setOutputDevices(outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005239 }
5240 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005241 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005242}
5243
5244void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5245{
5246 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005247 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005248 for (size_t i = 0; i < mOutputs.size(); i++) {
5249 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005250 for (const auto& client : outputDesc->getClientIterable()) {
5251 if (client->hasPreferredDevice() && client->uid() == uid) {
5252 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005253 auto clientStrategy = client->strategy();
5254 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5255 end(affectedStrategies)) {
5256 continue;
5257 }
5258 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005259 }
5260 }
5261 }
5262 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005263 for (const auto& strategy : affectedStrategies) {
5264 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005265 }
5266
5267 // remove input routes associated with this uid
5268 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005269 for (size_t i = 0; i < mInputs.size(); i++) {
5270 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005271 for (const auto& client : inputDesc->getClientIterable()) {
5272 if (client->hasPreferredDevice() && client->uid() == uid) {
5273 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5274 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005275 }
5276 }
5277 }
5278 // reroute inputs if necessary
5279 SortedVector<audio_io_handle_t> inputsToClose;
5280 for (size_t i = 0; i < mInputs.size(); i++) {
5281 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005282 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005283 inputsToClose.add(inputDesc->mIoHandle);
5284 }
5285 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005286 for (const auto& input : inputsToClose) {
5287 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005288 }
5289}
5290
Eric Laurentd60560a2015-04-10 11:31:20 -07005291void AudioPolicyManager::clearAudioSources(uid_t uid)
5292{
5293 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005294 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5295 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005296 stopAudioSource(mAudioSources.keyAt(i));
5297 }
5298 }
5299}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005300
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005301status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5302 audio_io_handle_t *ioHandle,
5303 audio_devices_t *device)
5304{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005305 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5306 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005307 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01005308 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005309
François Gaffiedf372692015-03-19 10:43:27 +01005310 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005311}
5312
Eric Laurentd60560a2015-04-10 11:31:20 -07005313status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005314 const audio_attributes_t *attributes,
5315 audio_port_handle_t *portId,
5316 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005317{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005318 ALOGV("%s", __FUNCTION__);
5319 *portId = AUDIO_PORT_HANDLE_NONE;
5320
5321 if (source == NULL || attributes == NULL || portId == NULL) {
5322 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5323 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005324 return BAD_VALUE;
5325 }
5326
Eric Laurentd60560a2015-04-10 11:31:20 -07005327 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5328 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005329 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5330 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005331 return INVALID_OPERATION;
5332 }
5333
François Gaffie11d30102018-11-02 16:09:09 +01005334 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005335 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005336 String8(source->ext.device.address),
5337 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005338 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005339 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005340 return BAD_VALUE;
5341 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005342
jiabin4ef93452019-09-10 14:29:54 -07005343 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005344
François Gaffieaaac0fd2018-11-22 17:56:39 +01005345 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005346 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005347 mEngine->getStreamTypeForAttributes(*attributes),
5348 mEngine->getProductStrategyForAttributes(*attributes),
5349 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005350
5351 status_t status = connectAudioSource(sourceDesc);
5352 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005353 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005354 }
5355 return status;
5356}
5357
Francois Gaffie601801d2021-06-22 13:27:39 +02005358sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5359 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5360{
5361 ALOGV("%s", __FUNCTION__);
5362 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5363
5364 status_t status = startAudioSource(source, attributes, &portId, uid);
5365 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5366 return mAudioSources.valueFor(portId);
5367}
5368
5369
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005370status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005371{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005372 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005373
5374 // make sure we only have one patch per source.
5375 disconnectAudioSource(sourceDesc);
5376
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005377 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005378 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5379 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5380 sourceDesc->srcDevice()->type(),
5381 String8(sourceDesc->srcDevice()->address().c_str()),
5382 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005383 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005384 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005385 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005386 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005387 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5388 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5389 return INVALID_OPERATION;
5390 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005391 PatchBuilder patchBuilder;
5392 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5393 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005394
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005395 return connectAudioSourceToSink(
5396 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005397}
5398
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005399status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005400{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005401 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5402 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005403 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005404 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005405 return BAD_VALUE;
5406 }
5407 status_t status = disconnectAudioSource(sourceDesc);
5408
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005409 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005410 return status;
5411}
5412
Andy Hung2ddee192015-12-18 17:34:44 -08005413status_t AudioPolicyManager::setMasterMono(bool mono)
5414{
5415 if (mMasterMono == mono) {
5416 return NO_ERROR;
5417 }
5418 mMasterMono = mono;
5419 // if enabling mono we close all offloaded devices, which will invalidate the
5420 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5421 // for recreating the new AudioTrack as non-offloaded PCM.
5422 //
5423 // If disabling mono, we leave all tracks as is: we don't know which clients
5424 // and tracks are able to be recreated as offloaded. The next "song" should
5425 // play back offloaded.
5426 if (mMasterMono) {
5427 Vector<audio_io_handle_t> offloaded;
5428 for (size_t i = 0; i < mOutputs.size(); ++i) {
5429 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5430 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5431 offloaded.push(desc->mIoHandle);
5432 }
5433 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005434 for (const auto& handle : offloaded) {
5435 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005436 }
5437 }
5438 // update master mono for all remaining outputs
5439 for (size_t i = 0; i < mOutputs.size(); ++i) {
5440 updateMono(mOutputs.keyAt(i));
5441 }
5442 return NO_ERROR;
5443}
5444
5445status_t AudioPolicyManager::getMasterMono(bool *mono)
5446{
5447 *mono = mMasterMono;
5448 return NO_ERROR;
5449}
5450
Eric Laurentac9cef52017-06-09 15:46:26 -07005451float AudioPolicyManager::getStreamVolumeDB(
5452 audio_stream_type_t stream, int index, audio_devices_t device)
5453{
jiabin9a3361e2019-10-01 09:38:30 -07005454 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005455}
5456
jiabin81772902018-04-02 17:52:27 -07005457status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5458 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005459 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005460{
Kriti Dang6537def2021-03-02 13:46:59 +01005461 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5462 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005463 return BAD_VALUE;
5464 }
Kriti Dang6537def2021-03-02 13:46:59 +01005465 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5466 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005467
5468 size_t formatsWritten = 0;
5469 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005470
Kriti Dang6537def2021-03-02 13:46:59 +01005471 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005472 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5473 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005474 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005475 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005476 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005477 bool formatEnabled = true;
5478 switch (forceUse) {
5479 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005480 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005481 break;
5482 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5483 formatEnabled = false;
5484 break;
5485 default: // AUTO or ALWAYS => true
5486 break;
jiabin81772902018-04-02 17:52:27 -07005487 }
5488 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5489 }
jiabin81772902018-04-02 17:52:27 -07005490 }
5491 return NO_ERROR;
5492}
5493
Kriti Dang6537def2021-03-02 13:46:59 +01005494status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5495 audio_format_t *surroundFormats) {
5496 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5497 return BAD_VALUE;
5498 }
5499 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5500 __func__, *numSurroundFormats, surroundFormats);
5501
5502 size_t formatsWritten = 0;
5503 size_t formatsMax = *numSurroundFormats;
5504 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5505
5506 // Return formats from all device profiles that have already been resolved by
5507 // checkOutputsForDevice().
5508 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5509 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5510 audio_devices_t deviceType = device->type();
5511 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5512 // returns formats reported by HDMI devices.
5513 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5514 continue;
5515 }
5516 // Formats reported by sink devices
5517 std::unordered_set<audio_format_t> formatset;
5518 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5519 formatset.insert(it->second.begin(), it->second.end());
5520 }
5521
5522 // Formats hard-coded in the in policy configuration file (if any).
5523 FormatVector encodedFormats = device->encodedFormats();
5524 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5525 // Filter the formats which are supported by the vendor hardware.
5526 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5527 if (mConfig.getSurroundFormats().count(*it) != 0) {
5528 formats.insert(*it);
5529 } else {
5530 for (const auto& pair : mConfig.getSurroundFormats()) {
5531 if (pair.second.count(*it) != 0) {
5532 formats.insert(pair.first);
5533 break;
5534 }
5535 }
5536 }
5537 }
5538 }
5539 *numSurroundFormats = formats.size();
5540 for (const auto& format: formats) {
5541 if (formatsWritten < formatsMax) {
5542 surroundFormats[formatsWritten++] = format;
5543 }
5544 }
5545 return NO_ERROR;
5546}
5547
jiabin81772902018-04-02 17:52:27 -07005548status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5549{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005550 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005551 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5552 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005553 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005554 return BAD_VALUE;
5555 }
5556
Mikhail Naganov100f0122018-11-29 11:22:16 -08005557 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5558 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005559 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005560 return INVALID_OPERATION;
5561 }
5562
Mikhail Naganov100f0122018-11-29 11:22:16 -08005563 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005564 return NO_ERROR;
5565 }
5566
Mikhail Naganov100f0122018-11-29 11:22:16 -08005567 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005568 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005569 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005570 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005571 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005572 }
5573 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005574 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005575 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005576 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005577 }
5578 }
5579
5580 sp<SwAudioOutputDescriptor> outputDesc;
5581 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005582 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5583 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005584 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5585 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005586 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005587 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005588 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5589 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5590 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005591 name.c_str(),
5592 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005593 if (status != NO_ERROR) {
5594 continue;
5595 }
5596 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5597 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5598 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005599 name.c_str(),
5600 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005601 profileUpdated |= (status == NO_ERROR);
5602 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005603 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005604 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005605 AUDIO_DEVICE_IN_HDMI);
5606 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5607 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005608 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005609 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005610 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5611 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5612 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005613 name.c_str(),
5614 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005615 if (status != NO_ERROR) {
5616 continue;
5617 }
5618 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5619 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5620 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005621 name.c_str(),
5622 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005623 profileUpdated |= (status == NO_ERROR);
5624 }
5625
jiabin81772902018-04-02 17:52:27 -07005626 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005627 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005628 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005629 }
5630
5631 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5632}
5633
Eric Laurent5ada82e2019-08-29 17:53:54 -07005634void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005635{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005636 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005637 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005638 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005639 }
5640}
5641
jiabin6012f912018-11-02 17:06:30 -07005642bool AudioPolicyManager::isHapticPlaybackSupported()
5643{
5644 for (const auto& hwModule : mHwModules) {
5645 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5646 for (const auto &outProfile : outputProfiles) {
5647 struct audio_port audioPort;
5648 outProfile->toAudioPort(&audioPort);
5649 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5650 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5651 return true;
5652 }
5653 }
5654 }
5655 }
5656 return false;
5657}
5658
Carter Hsu325a8eb2022-01-19 19:56:51 +08005659bool AudioPolicyManager::isUltrasoundSupported()
5660{
5661 bool hasUltrasoundOutput = false;
5662 bool hasUltrasoundInput = false;
5663 for (const auto& hwModule : mHwModules) {
5664 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5665 if (!hasUltrasoundOutput) {
5666 for (const auto &outProfile : outputProfiles) {
5667 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5668 hasUltrasoundOutput = true;
5669 break;
5670 }
5671 }
5672 }
5673
5674 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5675 if (!hasUltrasoundInput) {
5676 for (const auto &inputProfile : inputProfiles) {
5677 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5678 hasUltrasoundInput = true;
5679 break;
5680 }
5681 }
5682 }
5683
5684 if (hasUltrasoundOutput && hasUltrasoundInput)
5685 return true;
5686 }
5687 return false;
5688}
5689
Atneya Nair698f5ef2022-12-15 16:15:09 -08005690bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5691{
5692 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5693 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5694 for (const auto& hwModule : mHwModules) {
5695 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5696 for (const auto &inputProfile : inputProfiles) {
5697 if ((inputProfile->getFlags() & mask) == mask) {
5698 return true;
5699 }
5700 }
5701 }
5702 return false;
5703}
5704
Eric Laurent8340e672019-11-06 11:01:08 -08005705bool AudioPolicyManager::isCallScreenModeSupported()
5706{
5707 return getConfig().isCallScreenModeSupported();
5708}
5709
5710
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005711status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005712{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005713 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005714 if (!sourceDesc->isConnected()) {
5715 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5716 return NO_ERROR;
5717 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005718 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5719 if (swOutput != 0) {
5720 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005721 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005722 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005723 }
jiabinbce0c1d2020-10-05 11:20:18 -07005724 if (releaseOutput(sourceDesc->portId())) {
5725 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5726 // no need to release audio patch here but just return NO_ERROR.
5727 return NO_ERROR;
5728 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005729 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005730 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005731 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005732 // close Hwoutput and remove from mHwOutputs
5733 } else {
5734 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5735 }
5736 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005737 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005738 sourceDesc->disconnect();
5739 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005740}
5741
François Gaffiec005e562018-11-06 15:04:49 +01005742sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5743 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005744{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005745 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005746 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005747 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005748 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005749 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5750 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005751 source = sourceDesc;
5752 break;
5753 }
5754 }
5755 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005756}
5757
Eric Laurentb4f42a92022-01-17 17:37:31 +01005758bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005759 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005760 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005761{
5762 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5763 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005764 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005765 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005766 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5767 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5768 return false;
5769 }
5770 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5771 return false;
5772 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005773 }
5774
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005775 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005776 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005777 if (profile == nullptr) {
5778 return false;
5779 }
5780
5781 // The caller can have the audio config criteria ignored by either passing a null ptr or
5782 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005783 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005784 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005785
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005786 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005787 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005788 return false;
5789 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005790 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005791 return true;
5792}
5793
5794void AudioPolicyManager::checkVirtualizerClientRoutes() {
5795 std::set<audio_stream_type_t> streamsToInvalidate;
5796 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005797 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5798 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005799 audio_attributes_t attr = client->attributes();
5800 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5801 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5802 audio_config_base_t clientConfig = client->config();
5803 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005804 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005805 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005806 streamsToInvalidate.insert(client->stream());
5807 }
5808 }
5809 }
5810
jiabinc44b3462022-12-08 12:52:31 -08005811 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005812}
5813
Eric Laurente191d1b2022-04-15 11:59:25 +02005814
5815bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5816 const sp<SwAudioOutputDescriptor>& outputDesc) {
5817 if (outputDesc->isDuplicated()) {
5818 return false;
5819 }
5820 DeviceVector devices = outputDesc->supportedDevices();
5821 for (size_t i = 0; i < mOutputs.size(); i++) {
5822 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5823 if (desc == outputDesc || desc->isDuplicated()) {
5824 continue;
5825 }
5826 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5827 if (!sharedDevices.isEmpty()
5828 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5829 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5830 return false;
5831 }
5832 }
5833 return true;
5834}
5835
5836
Eric Laurentfa0f6742021-08-17 18:39:44 +02005837status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005838 const audio_attributes_t *attr,
5839 audio_io_handle_t *output) {
5840 *output = AUDIO_IO_HANDLE_NONE;
5841
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005842 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5843 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5844 audio_config_t *configPtr = nullptr;
5845 audio_config_t config;
5846 if (mixerConfig != nullptr) {
5847 config = audio_config_initializer(mixerConfig);
5848 configPtr = &config;
5849 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005850 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005851 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005852 return BAD_VALUE;
5853 }
5854
5855 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005856 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005857 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005858 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005859 return BAD_VALUE;
5860 }
5861
Eric Laurente191d1b2022-04-15 11:59:25 +02005862 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005863 for (size_t i = 0; i < mOutputs.size(); i++) {
5864 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005865 if (!desc->isDuplicated()
5866 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5867 spatializerOutputs.push_back(desc);
5868 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005869 }
5870 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005871 mSpatializerOutput.clear();
5872 bool outputsChanged = false;
5873 for (const auto& desc : spatializerOutputs) {
5874 if (desc->mProfile == profile
5875 && (configPtr == nullptr
5876 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5877 mSpatializerOutput = desc;
5878 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5879 } else {
5880 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5881 " and devices %s", __func__, desc->mIoHandle,
5882 configPtr != nullptr ? configPtr->channel_mask : 0,
5883 devices.toString().c_str());
5884 closeOutput(desc->mIoHandle);
5885 outputsChanged = true;
5886 }
Eric Laurent39095982021-08-24 18:29:27 +02005887 }
5888
Eric Laurente191d1b2022-04-15 11:59:25 +02005889 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005890 sp<SwAudioOutputDescriptor> desc =
5891 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005892 if (desc != nullptr) {
5893 mSpatializerOutput = desc;
5894 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005895 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005896 }
5897
5898 checkVirtualizerClientRoutes();
5899
Eric Laurente191d1b2022-04-15 11:59:25 +02005900 if (outputsChanged) {
5901 mPreviousOutputs = mOutputs;
5902 mpClientInterface->onAudioPortListUpdate();
5903 }
5904
5905 if (mSpatializerOutput == nullptr) {
5906 ALOGV("%s could not open spatializer output with requested config", __func__);
5907 return BAD_VALUE;
5908 }
Eric Laurent39095982021-08-24 18:29:27 +02005909 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005910 ALOGV("%s returning new spatializer output %d", __func__, *output);
5911 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005912}
5913
Eric Laurentfa0f6742021-08-17 18:39:44 +02005914status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5915 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005916 return INVALID_OPERATION;
5917 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005918 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005919 return BAD_VALUE;
5920 }
Eric Laurent39095982021-08-24 18:29:27 +02005921
Eric Laurente191d1b2022-04-15 11:59:25 +02005922 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5923 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5924 closeOutput(mSpatializerOutput->mIoHandle);
5925 //from now on mSpatializerOutput is null
5926 checkVirtualizerClientRoutes();
5927 }
Eric Laurent39095982021-08-24 18:29:27 +02005928
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005929 return NO_ERROR;
5930}
5931
Eric Laurente552edb2014-03-10 17:42:56 -07005932// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005933// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005934// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005935uint32_t AudioPolicyManager::nextAudioPortGeneration()
5936{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005937 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005938}
5939
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005940static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005941 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5942 !audioPolicyXmlConfigFile.empty()) {
5943 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5944 if (ret == NO_ERROR) {
5945 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005946 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005947 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005948 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005949 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005950}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005951
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005952AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5953 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005954 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005955 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005956 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005957 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005958 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005959 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005960 mAudioPortGeneration(1),
5961 mBeaconMuteRefCount(0),
5962 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005963 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005964 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005965 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005966 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005967{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005968}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005969
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005970AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5971 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5972{
5973 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005974}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005975
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005976void AudioPolicyManager::loadConfig() {
5977 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005978 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005979 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005980 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005981}
5982
5983status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005984 {
5985 auto engLib = EngineLibrary::load(
5986 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5987 if (!engLib) {
5988 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5989 return NO_INIT;
5990 }
5991 mEngine = engLib->createEngine();
5992 if (mEngine == nullptr) {
5993 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5994 return NO_INIT;
5995 }
François Gaffie2110e042015-03-24 08:41:51 +01005996 }
5997 mEngine->setObserver(this);
5998 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005999 if (status != NO_ERROR) {
6000 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6001 return status;
6002 }
François Gaffie2110e042015-03-24 08:41:51 +01006003
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006004 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006005 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6006 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6007
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006008 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006009 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006010 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006011
Eric Laurent3a4311c2014-03-17 12:00:47 -07006012 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01006013 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
6014 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
6015 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006016 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006017 }
jiabin9ff780e2018-03-19 18:19:52 -07006018 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07006019 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07006020 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07006021 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07006022 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07006023 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07006024 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07006025 }
6026 }
6027 }
Eric Laurente552edb2014-03-10 17:42:56 -07006028
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006029 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006030
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006031 // Silence ALOGV statements
6032 property_set("log.tag." LOG_TAG, "D");
6033
Eric Laurente552edb2014-03-10 17:42:56 -07006034 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006035 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006036}
6037
Eric Laurente0720872014-03-11 09:30:41 -07006038AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006039{
Eric Laurente552edb2014-03-10 17:42:56 -07006040 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006041 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006042 }
6043 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006044 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006045 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006046 mAvailableOutputDevices.clear();
6047 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006048 mOutputs.clear();
6049 mInputs.clear();
6050 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08006051 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006052 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006053}
6054
Eric Laurente0720872014-03-11 09:30:41 -07006055status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006056{
Eric Laurent87ffa392015-05-22 10:32:38 -07006057 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006058}
6059
Eric Laurente552edb2014-03-10 17:42:56 -07006060// ---
6061
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006062void AudioPolicyManager::onNewAudioModulesAvailable()
6063{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006064 DeviceVector newDevices;
6065 onNewAudioModulesAvailableInt(&newDevices);
6066 if (!newDevices.empty()) {
6067 nextAudioPortGeneration();
6068 mpClientInterface->onAudioPortListUpdate();
6069 }
6070}
6071
6072void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6073{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006074 for (const auto& hwModule : mHwModulesAll) {
6075 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6076 continue;
6077 }
6078 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
6079 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
6080 ALOGW("could not open HW module %s", hwModule->getName());
6081 continue;
6082 }
6083 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006084 // open all output streams needed to access attached devices.
6085 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006086 // This also validates mAvailableOutputDevices list
6087 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6088 if (!outProfile->canOpenNewIo()) {
6089 ALOGE("Invalid Output profile max open count %u for profile %s",
6090 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6091 continue;
6092 }
6093 if (!outProfile->hasSupportedDevices()) {
6094 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6095 continue;
6096 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006097 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6098 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006099 mTtsOutputAvailable = true;
6100 }
6101
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006102 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
6103 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
6104 sp<DeviceDescriptor> supportedDevice = 0;
6105 if (supportedDevices.contains(mDefaultOutputDevice)) {
6106 supportedDevice = mDefaultOutputDevice;
6107 } else {
6108 // choose first device present in profile's SupportedDevices also part of
6109 // mAvailableOutputDevices.
6110 if (availProfileDevices.isEmpty()) {
6111 continue;
6112 }
6113 supportedDevice = availProfileDevices.itemAt(0);
6114 }
6115 if (!mOutputDevicesAll.contains(supportedDevice)) {
6116 continue;
6117 }
6118 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6119 mpClientInterface);
6120 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006121 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6122 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006123 AUDIO_STREAM_DEFAULT,
6124 AUDIO_OUTPUT_FLAG_NONE, &output);
6125 if (status != NO_ERROR) {
6126 ALOGW("Cannot open output stream for devices %s on hw module %s",
6127 supportedDevice->toString().c_str(), hwModule->getName());
6128 continue;
6129 }
6130 for (const auto &device : availProfileDevices) {
6131 // give a valid ID to an attached device once confirmed it is reachable
6132 if (!device->isAttached()) {
6133 device->attach(hwModule);
6134 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006135 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006136 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006137 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6138 }
6139 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006140 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006141 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6142 mPrimaryOutput = outputDesc;
6143 }
Eric Laurent39095982021-08-24 18:29:27 +02006144 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006145 outputDesc->close();
6146 } else {
6147 addOutput(output, outputDesc);
6148 setOutputDevices(outputDesc,
6149 DeviceVector(supportedDevice),
6150 true,
6151 0,
6152 NULL);
6153 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006154 }
6155 // open input streams needed to access attached devices to validate
6156 // mAvailableInputDevices list
6157 for (const auto& inProfile : hwModule->getInputProfiles()) {
6158 if (!inProfile->canOpenNewIo()) {
6159 ALOGE("Invalid Input profile max open count %u for profile %s",
6160 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6161 continue;
6162 }
6163 if (!inProfile->hasSupportedDevices()) {
6164 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6165 continue;
6166 }
6167 // chose first device present in profile's SupportedDevices also part of
6168 // available input devices
6169 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
6170 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
6171 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006172 ALOGV("%s: Input device list is empty! for profile %s",
6173 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006174 continue;
6175 }
6176 sp<AudioInputDescriptor> inputDesc =
6177 new AudioInputDescriptor(inProfile, mpClientInterface);
6178
6179 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6180 status_t status = inputDesc->open(nullptr,
6181 availProfileDevices.itemAt(0),
6182 AUDIO_SOURCE_MIC,
6183 AUDIO_INPUT_FLAG_NONE,
6184 &input);
6185 if (status != NO_ERROR) {
6186 ALOGW("Cannot open input stream for device %s on hw module %s",
6187 availProfileDevices.toString().c_str(),
6188 hwModule->getName());
6189 continue;
6190 }
6191 for (const auto &device : availProfileDevices) {
6192 // give a valid ID to an attached device once confirmed it is reachable
6193 if (!device->isAttached()) {
6194 device->attach(hwModule);
6195 device->importAudioPortAndPickAudioProfile(inProfile, true);
6196 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006197 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006198 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6199 }
6200 }
6201 inputDesc->close();
6202 }
6203 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006204
6205 // Check if spatializer outputs can be closed until used.
6206 // mOutputs vector never contains duplicated outputs at this point.
6207 std::vector<audio_io_handle_t> outputsClosed;
6208 for (size_t i = 0; i < mOutputs.size(); i++) {
6209 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6210 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6211 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6212 outputsClosed.push_back(desc->mIoHandle);
6213 desc->close();
6214 }
6215 }
6216 for (auto output : outputsClosed) {
6217 removeOutput(output);
6218 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006219}
6220
Eric Laurent98e38192018-02-15 18:31:53 -08006221void AudioPolicyManager::addOutput(audio_io_handle_t output,
6222 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006223{
Eric Laurent1c333e22014-05-20 10:48:17 -07006224 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006225 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006226 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006227 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006228 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006229}
6230
François Gaffie53615e22015-03-19 09:24:12 +01006231void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6232{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006233 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6234 ALOGV("%s: removing primary output", __func__);
6235 mPrimaryOutput = nullptr;
6236 }
François Gaffie53615e22015-03-19 09:24:12 +01006237 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006238 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006239}
6240
Eric Laurent98e38192018-02-15 18:31:53 -08006241void AudioPolicyManager::addInput(audio_io_handle_t input,
6242 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006243{
Eric Laurent1c333e22014-05-20 10:48:17 -07006244 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006245 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006246}
Eric Laurente552edb2014-03-10 17:42:56 -07006247
François Gaffie11d30102018-11-02 16:09:09 +01006248status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006249 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006250 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006251{
François Gaffie11d30102018-11-02 16:09:09 +01006252 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006253 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006254 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006255
François Gaffie11d30102018-11-02 16:09:09 +01006256 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006257 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006258 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006259 }
Eric Laurente552edb2014-03-10 17:42:56 -07006260
Eric Laurent3b73df72014-03-11 09:06:29 -07006261 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006262 // first call getAudioPort to get the supported attributes from the HAL
6263 struct audio_port_v7 port = {};
6264 device->toAudioPort(&port);
6265 status_t status = mpClientInterface->getAudioPort(&port);
6266 if (status == NO_ERROR) {
6267 device->importAudioPort(port);
6268 }
6269
6270 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006271 for (size_t i = 0; i < mOutputs.size(); i++) {
6272 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006273 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006274 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006275 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6276 mOutputs.keyAt(i), device->toString().c_str());
6277 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006278 }
6279 }
6280 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006281 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006282 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006283 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6284 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006285 if (profile->supportsDevice(device)) {
6286 profiles.add(profile);
6287 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6288 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006289 }
6290 }
6291 }
6292
Eric Laurent7b279bb2015-12-14 10:18:23 -08006293 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006294
Eric Laurente552edb2014-03-10 17:42:56 -07006295 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006296 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006297 return BAD_VALUE;
6298 }
6299
6300 // open outputs for matching profiles if needed. Direct outputs are also opened to
6301 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6302 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006303 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006304
6305 // nothing to do if one output is already opened for this profile
6306 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006307 for (j = 0; j < outputs.size(); j++) {
6308 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006309 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006310 // matching profile: save the sample rates, format and channel masks supported
6311 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006312 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006313 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006314 }
Eric Laurente552edb2014-03-10 17:42:56 -07006315 break;
6316 }
6317 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006318 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006319 continue;
6320 }
6321
Eric Laurent3974e3b2017-12-07 17:58:43 -08006322 if (!profile->canOpenNewIo()) {
6323 ALOGW("Max Output number %u already opened for this profile %s",
6324 profile->maxOpenCount, profile->getTagName().c_str());
6325 continue;
6326 }
6327
Eric Laurent83efe1c2017-07-09 16:51:08 -07006328 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07006329 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006330 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6331 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006332 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006333 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006334 profiles.removeAt(profile_index);
6335 profile_index--;
6336 } else {
6337 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006338 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006339 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006340 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6341 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006342 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006343 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006344
François Gaffie11d30102018-11-02 16:09:09 +01006345 if (device_distinguishes_on_address(deviceType)) {
6346 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6347 device->toString().c_str());
6348 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
6349 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006350 }
Eric Laurente552edb2014-03-10 17:42:56 -07006351 ALOGV("checkOutputsForDevice(): adding output %d", output);
6352 }
6353 }
6354
6355 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006356 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006357 return BAD_VALUE;
6358 }
Eric Laurentd4692962014-05-05 18:13:44 -07006359 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006360 // check if one opened output is not needed any more after disconnecting one device
6361 for (size_t i = 0; i < mOutputs.size(); i++) {
6362 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006363 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006364 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006365 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006366 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006367 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006368 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006369 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6370 mOutputs.keyAt(i));
6371 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006372 }
Eric Laurente552edb2014-03-10 17:42:56 -07006373 }
6374 }
Eric Laurentd4692962014-05-05 18:13:44 -07006375 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006376 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006377 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6378 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006379 if (!profile->supportsDevice(device)) {
6380 continue;
6381 }
6382 ALOGV("checkOutputsForDevice(): "
6383 "clearing direct output profile %zu on module %s",
6384 j, hwModule->getName());
6385 profile->clearAudioProfiles();
6386 if (!profile->hasDynamicAudioProfile()) {
6387 continue;
6388 }
6389 // When a device is disconnected, if there is an IOProfile that contains dynamic
6390 // profiles and supports the disconnected device, call getAudioPort to repopulate
6391 // the capabilities of the devices that is supported by the IOProfile.
6392 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6393 if (supportedDevice == device ||
6394 !mAvailableOutputDevices.contains(supportedDevice)) {
6395 continue;
6396 }
6397 struct audio_port_v7 port;
6398 supportedDevice->toAudioPort(&port);
6399 status_t status = mpClientInterface->getAudioPort(&port);
6400 if (status == NO_ERROR) {
6401 supportedDevice->importAudioPort(port);
6402 }
Eric Laurente552edb2014-03-10 17:42:56 -07006403 }
6404 }
6405 }
6406 }
6407 return NO_ERROR;
6408}
6409
François Gaffie11d30102018-11-02 16:09:09 +01006410status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006411 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006412{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006413 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006414
François Gaffie11d30102018-11-02 16:09:09 +01006415 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006416 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006417 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006418 }
6419
Eric Laurentd4692962014-05-05 18:13:44 -07006420 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006421 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006422 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006423 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006424 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006425 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006426 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006427 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006428
François Gaffie11d30102018-11-02 16:09:09 +01006429 if (profile->supportsDevice(device)) {
6430 profiles.add(profile);
6431 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6432 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006433 }
6434 }
6435 }
6436
Eric Laurent0dd51852019-04-19 18:18:58 -07006437 if (profiles.isEmpty()) {
6438 ALOGW("%s: No input profile available for device %s",
6439 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006440 return BAD_VALUE;
6441 }
6442
6443 // open inputs for matching profiles if needed. Direct inputs are also opened to
6444 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6445 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6446
Eric Laurent1c333e22014-05-20 10:48:17 -07006447 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006448
Eric Laurentd4692962014-05-05 18:13:44 -07006449 // nothing to do if one input is already opened for this profile
6450 size_t input_index;
6451 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6452 desc = mInputs.valueAt(input_index);
6453 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006454 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006455 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006456 }
Eric Laurentd4692962014-05-05 18:13:44 -07006457 break;
6458 }
6459 }
6460 if (input_index != mInputs.size()) {
6461 continue;
6462 }
6463
Eric Laurent3974e3b2017-12-07 17:58:43 -08006464 if (!profile->canOpenNewIo()) {
6465 ALOGW("Max Input number %u already opened for this profile %s",
6466 profile->maxOpenCount, profile->getTagName().c_str());
6467 continue;
6468 }
6469
Eric Laurentfe231122017-11-17 17:48:06 -08006470 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006471 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006472 status_t status = desc->open(nullptr,
6473 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006474 AUDIO_SOURCE_MIC,
6475 AUDIO_INPUT_FLAG_NONE,
6476 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006477
Eric Laurentcf2c0212014-07-25 16:20:43 -07006478 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006479 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006480 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006481 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006482 mpClientInterface->setParameters(input, String8(param));
6483 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006484 }
François Gaffie11d30102018-11-02 16:09:09 +01006485 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006486 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006487 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006488 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006489 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006490 }
6491
Eric Laurent0dd51852019-04-19 18:18:58 -07006492 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006493 addInput(input, desc);
6494 }
6495 } // endif input != 0
6496
Eric Laurentcf2c0212014-07-25 16:20:43 -07006497 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006498 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006499 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006500 profiles.removeAt(profile_index);
6501 profile_index--;
6502 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006503 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006504 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006505 }
Eric Laurentd4692962014-05-05 18:13:44 -07006506 ALOGV("checkInputsForDevice(): adding input %d", input);
6507 }
6508 } // end scan profiles
6509
6510 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006511 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006512 return BAD_VALUE;
6513 }
6514 } else {
6515 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006516 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006517 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006518 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006519 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006520 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006521 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006522 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006523 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6524 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006525 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006526 }
6527 }
6528 }
6529 } // end disconnect
6530
6531 return NO_ERROR;
6532}
6533
6534
Eric Laurente0720872014-03-11 09:30:41 -07006535void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006536{
6537 ALOGV("closeOutput(%d)", output);
6538
François Gaffie1c878552018-11-22 16:53:21 +01006539 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6540 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006541 ALOGW("closeOutput() unknown output %d", output);
6542 return;
6543 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006544 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006545 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006546
Eric Laurente552edb2014-03-10 17:42:56 -07006547 // look for duplicated outputs connected to the output being removed.
6548 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006549 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6550 if (dupOutput->isDuplicated() &&
6551 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6552 sp<SwAudioOutputDescriptor> remainingOutput =
6553 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006554 // As all active tracks on duplicated output will be deleted,
6555 // and as they were also referenced on the other output, the reference
6556 // count for their stream type must be adjusted accordingly on
6557 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006558 const bool wasActive = remainingOutput->isActive();
6559 // Note: no-op on the closing output where all clients has already been set inactive
6560 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006561 // stop() will be a no op if the output is still active but is needed in case all
6562 // active streams refcounts where cleared above
6563 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006564 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006565 }
Eric Laurente552edb2014-03-10 17:42:56 -07006566 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6567 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6568
6569 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006570 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006571 }
6572 }
6573
Eric Laurent05b90f82014-08-27 15:32:29 -07006574 nextAudioPortGeneration();
6575
François Gaffie1c878552018-11-22 16:53:21 +01006576 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006577 if (index >= 0) {
6578 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006579 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6580 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006581 mAudioPatches.removeItemsAt(index);
6582 mpClientInterface->onAudioPatchListUpdate();
6583 }
6584
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006585 if (closingOutputWasActive) {
6586 closingOutput->stop();
6587 }
François Gaffie1c878552018-11-22 16:53:21 +01006588 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006589
François Gaffie53615e22015-03-19 09:24:12 +01006590 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006591 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006592 if (closingOutput == mSpatializerOutput) {
6593 mSpatializerOutput.clear();
6594 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006595
6596 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6597 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006598 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006599 bool directOutputOpen = false;
6600 for (size_t i = 0; i < mOutputs.size(); i++) {
6601 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6602 directOutputOpen = true;
6603 break;
6604 }
6605 }
6606 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006607 ALOGV("no direct outputs open, reset MSD patches");
6608 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6609 // how output devices for patching are resolved. Avoid by caching and reusing the
6610 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6611 // devices to patch to. This may be complicated by the fact that devices may become
6612 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006613 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006614 }
6615 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006616}
6617
6618void AudioPolicyManager::closeInput(audio_io_handle_t input)
6619{
6620 ALOGV("closeInput(%d)", input);
6621
6622 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6623 if (inputDesc == NULL) {
6624 ALOGW("closeInput() unknown input %d", input);
6625 return;
6626 }
6627
Eric Laurent6a94d692014-05-20 11:18:06 -07006628 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006629
François Gaffie11d30102018-11-02 16:09:09 +01006630 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006631 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006632 if (index >= 0) {
6633 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006634 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6635 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006636 mAudioPatches.removeItemsAt(index);
6637 mpClientInterface->onAudioPatchListUpdate();
6638 }
6639
Eric Laurentfe231122017-11-17 17:48:06 -08006640 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006641 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006642
François Gaffie11d30102018-11-02 16:09:09 +01006643 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6644 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006645 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006646 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006647 }
Eric Laurente552edb2014-03-10 17:42:56 -07006648}
6649
François Gaffie11d30102018-11-02 16:09:09 +01006650SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6651 const DeviceVector &devices,
6652 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006653{
6654 SortedVector<audio_io_handle_t> outputs;
6655
François Gaffie11d30102018-11-02 16:09:09 +01006656 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006657 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006658 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006659 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006660 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006661 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006662 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006663 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006664 outputs.add(openOutputs.keyAt(i));
6665 }
6666 }
6667 return outputs;
6668}
6669
Mikhail Naganov37977152018-07-11 15:54:44 -07006670void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6671{
6672 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6673 // output is suspended before any tracks are moved to it
6674 checkA2dpSuspend();
6675 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006676 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006677 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006678 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006679 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006680 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6681 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6682 // configuration changes will ultimately be rerouted correctly. We can still avoid
6683 // unnecessary rerouting by caching and reusing the arguments to
6684 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6685 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006686 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006687 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006688 // an event that changed routing likely occurred, inform upper layers
6689 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006690}
6691
François Gaffiec005e562018-11-06 15:04:49 +01006692bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6693 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006694{
François Gaffiec005e562018-11-06 15:04:49 +01006695 return mEngine->getProductStrategyForAttributes(lAttr) ==
6696 mEngine->getProductStrategyForAttributes(rAttr);
6697}
6698
Francois Gaffieff1eb522020-05-06 18:37:04 +02006699void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6700{
6701 for (size_t i = 0; i < mAudioSources.size(); i++) {
6702 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6703 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006704 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006705 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006706 connectAudioSource(sourceDesc);
6707 }
6708 }
6709}
6710
6711void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6712{
6713 for (size_t i = 0; i < mAudioSources.size(); i++) {
6714 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6715 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6716 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6717 disconnectAudioSource(sourceDesc);
6718 }
6719 }
6720}
6721
François Gaffiec005e562018-11-06 15:04:49 +01006722void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6723{
6724 auto psId = mEngine->getProductStrategyForAttributes(attr);
6725
6726 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6727 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006728
François Gaffie11d30102018-11-02 16:09:09 +01006729 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6730 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006731
Eric Laurentc209fe42020-06-05 18:11:23 -07006732 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006733 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006734 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006735 // take into account dynamic audio policies related changes: if a client is now associated
6736 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006737 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006738 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6739 if (desc->isDuplicated()) {
6740 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006741 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006742 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6743 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6744 continue;
6745 }
6746 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006747 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006748 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6749 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6750 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006751 if (status != OK) {
6752 continue;
6753 }
yucliuf4de36d2020-09-14 14:57:56 -07006754 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006755 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006756 maxLatency = desc->latency();
6757 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006758 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006759 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006760 }
6761 }
6762
Eric Laurent56ed8842022-11-15 16:04:41 +01006763 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006764 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6765 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006766 for (audio_io_handle_t srcOut : srcOutputs) {
6767 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006768 if (desc == nullptr) continue;
6769
6770 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006771 maxLatency = desc->latency();
6772 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006773
Eric Laurent56ed8842022-11-15 16:04:41 +01006774 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006775 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006776 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006777 // a client on a non direct outputs has necessarily a linear PCM format
6778 // so we can call selectOutput() safely
6779 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6780 client->flags(),
6781 client->config().format,
6782 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006783 client->config().sample_rate,
6784 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006785 if (newOutput != srcOut) {
6786 invalidate = true;
6787 break;
6788 }
6789 } else {
6790 sp<IOProfile> profile = getProfileForOutput(newDevices,
6791 client->config().sample_rate,
6792 client->config().format,
6793 client->config().channel_mask,
6794 client->flags(),
6795 true /* directOnly */);
6796 if (profile != desc->mProfile) {
6797 invalidate = true;
6798 break;
6799 }
6800 }
6801 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006802 // mute strategy while moving tracks from one output to another
6803 if (invalidate) {
6804 invalidatedOutputs.push_back(desc);
6805 if (desc->isStrategyActive(psId)) {
6806 setStrategyMute(psId, true, desc);
6807 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6808 newDevices.types());
6809 }
Eric Laurente552edb2014-03-10 17:42:56 -07006810 }
François Gaffiec005e562018-11-06 15:04:49 +01006811 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006812 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006813 connectAudioSource(source);
6814 }
Eric Laurente552edb2014-03-10 17:42:56 -07006815 }
6816
Eric Laurent56ed8842022-11-15 16:04:41 +01006817 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6818 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6819 std::to_string(srcOutputs[0]).c_str(),
6820 std::to_string(dstOutputs[0]).c_str());
6821
François Gaffiec005e562018-11-06 15:04:49 +01006822 // Move effects associated to this stream from previous output to new output
6823 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006824 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006825 }
François Gaffiec005e562018-11-06 15:04:49 +01006826 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006827 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006828 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006829 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006830 desc->setTracksInvalidatedStatusByStrategy(psId);
6831 }
Eric Laurente552edb2014-03-10 17:42:56 -07006832 }
6833 }
6834}
6835
Eric Laurente0720872014-03-11 09:30:41 -07006836void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006837{
François Gaffiec005e562018-11-06 15:04:49 +01006838 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6839 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6840 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006841 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006842 }
Eric Laurente552edb2014-03-10 17:42:56 -07006843}
6844
Kevin Rocard153f92d2018-12-18 18:33:28 -08006845void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08006846 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006847 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006848 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006849 for (size_t i = 0; i < mOutputs.size(); i++) {
6850 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6851 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006852 sp<AudioPolicyMix> primaryMix;
6853 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006854 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006855 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6856 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
6857 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006858 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6859 for (auto &secondaryMix : secondaryMixes) {
6860 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6861 if (outputDesc != nullptr &&
6862 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6863 secondaryDescs.push_back(outputDesc);
6864 }
6865 }
6866
jiabinc44b3462022-12-08 12:52:31 -08006867 if (status != OK &&
6868 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
6869 // When it failed to query secondary output, only invalidate the client that is not
6870 // MMAP. The reason is that MMAP stream will not support secondary output.
6871 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00006872 } else if (!std::equal(
6873 client->getSecondaryOutputs().begin(),
6874 client->getSecondaryOutputs().end(),
6875 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006876 if (!audio_is_linear_pcm(client->config().format)) {
6877 // If the format is not PCM, the tracks should be invalidated to get correct
6878 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08006879 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00006880 } else {
6881 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6882 std::vector<audio_io_handle_t> secondaryOutputIds;
6883 for (const auto &secondaryDesc: secondaryDescs) {
6884 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6885 weakSecondaryDescs.push_back(secondaryDesc);
6886 }
6887 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6888 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006889 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006890 }
6891 }
6892 }
jiabin10a03f12021-05-07 23:46:28 +00006893 if (!trackSecondaryOutputs.empty()) {
6894 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6895 }
jiabinc44b3462022-12-08 12:52:31 -08006896 if (!clientsToInvalidate.empty()) {
6897 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
6898 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006899 }
6900}
6901
Eric Laurent2517af32020-11-25 15:31:27 +01006902bool AudioPolicyManager::isScoRequestedForComm() const {
6903 AudioDeviceTypeAddrVector devices;
6904 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6905 for (const auto &device : devices) {
6906 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6907 return true;
6908 }
6909 }
6910 return false;
6911}
6912
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006913bool AudioPolicyManager::isHearingAidUsedForComm() const {
6914 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6915 true /*fromCache*/);
6916 for (const auto &device : devices) {
6917 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6918 return true;
6919 }
6920 }
6921 return false;
6922}
6923
6924
Eric Laurente0720872014-03-11 09:30:41 -07006925void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006926{
François Gaffie53615e22015-03-19 09:24:12 +01006927 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006928 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006929 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006930 return;
6931 }
6932
Eric Laurent3a4311c2014-03-17 12:00:47 -07006933 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006934 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6935 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006936 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006937
6938 // if suspended, restore A2DP output if:
6939 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006940 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006941 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006942 //
Eric Laurentf732e072016-08-03 19:30:28 -07006943 // if not suspended, suspend A2DP output if:
6944 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006945 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006946 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006947 //
6948 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006949 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006950 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006951 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006952 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006953
6954 mpClientInterface->restoreOutput(a2dpOutput);
6955 mA2dpSuspended = false;
6956 }
6957 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006958 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006959 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006960 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006961 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006962
6963 mpClientInterface->suspendOutput(a2dpOutput);
6964 mA2dpSuspended = true;
6965 }
6966 }
6967}
6968
François Gaffie11d30102018-11-02 16:09:09 +01006969DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6970 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006971{
François Gaffie11d30102018-11-02 16:09:09 +01006972 DeviceVector devices;
6973
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006974 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006975 if (index >= 0) {
6976 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006977 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006978 ALOGV("%s device %s forced by patch %d", __func__,
6979 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6980 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006981 }
6982 }
6983
Dean Wheatley514b4312020-06-17 21:45:00 +10006984 // Do not retrieve engine device for outputs through MSD
6985 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6986 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6987 return outputDesc->devices();
6988 }
6989
Eric Laurent97ac8712018-07-27 18:59:02 -07006990 // Honor explicit routing requests only if no client using default routing is active on this
6991 // input: a specific app can not force routing for other apps by setting a preferred device.
6992 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006993 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006994 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006995 if (device != nullptr) {
6996 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006997 }
6998
François Gaffiea807ef92018-11-05 10:44:33 +01006999 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7000 // of setForceUse / Default Bus device here
7001 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7002 if (device != nullptr) {
7003 return DeviceVector(device);
7004 }
7005
François Gaffiec005e562018-11-06 15:04:49 +01007006 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7007 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7008 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307009 auto hasStreamActive = [&](auto stream) {
7010 return hasStream(streams, stream) && isStreamActive(stream, 0);
7011 };
Eric Laurent484e9272018-06-07 17:29:23 -07007012
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307013 auto doGetOutputDevicesForVoice = [&]() {
7014 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007015 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307016 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007017 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7018 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307019 };
7020
7021 // With low-latency playing on speaker, music on WFD, when the first low-latency
7022 // output is stopped, getNewOutputDevices checks for a product strategy
7023 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007024 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307025 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7026 // stream is associated to the output descriptor.
7027 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7028 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7029 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7030 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007031 // Retrieval of devices for voice DL is done on primary output profile, cannot
7032 // check the route (would force modifying configuration file for this profile)
7033 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7034 break;
7035 }
Eric Laurente552edb2014-03-10 17:42:56 -07007036 }
François Gaffiec005e562018-11-06 15:04:49 +01007037 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007038 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007039}
7040
François Gaffie11d30102018-11-02 16:09:09 +01007041sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7042 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007043{
François Gaffie11d30102018-11-02 16:09:09 +01007044 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007045
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007046 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007047 if (index >= 0) {
7048 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007049 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007050 ALOGV("getNewInputDevice() device %s forced by patch %d",
7051 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7052 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007053 }
7054 }
7055
Eric Laurent97ac8712018-07-27 18:59:02 -07007056 // Honor explicit routing requests only if no client using default routing is active on this
7057 // input: a specific app can not force routing for other apps by setting a preferred device.
7058 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007059 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7060 if (device != nullptr) {
7061 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007062 }
7063
Eric Laurentdc95a252018-04-12 12:46:56 -07007064 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007065 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007066 audio_attributes_t attributes;
7067 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007068 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007069 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7070 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007071 attributes = topClient->attributes();
7072 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007073 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007074 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007075 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7076 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007077 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007078 }
7079
Francois Gaffie716e1432019-01-14 16:58:59 +01007080 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7081 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007082 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007083 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007084 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007085 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007086
Eric Laurente552edb2014-03-10 17:42:56 -07007087 return device;
7088}
7089
Eric Laurent794fde22016-03-11 09:50:45 -08007090bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7091 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007092 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007093}
7094
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007095status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007096 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007097 if (devices == nullptr) {
7098 return BAD_VALUE;
7099 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007100
Andy Hung6d23c0f2022-02-16 09:37:15 -08007101 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007102 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7103 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007104 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007105 for (const auto& device : curDevices) {
7106 devices->push_back(device->getDeviceTypeAddr());
7107 }
7108 return NO_ERROR;
7109}
7110
Eric Laurente0720872014-03-11 09:30:41 -07007111void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007112 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007113 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007114 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007115 updateDevicesAndOutputs();
7116 break;
7117 default:
7118 break;
7119 }
7120}
7121
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007122uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007123
7124 // skip beacon mute management if a dedicated TTS output is available
7125 if (mTtsOutputAvailable) {
7126 return 0;
7127 }
7128
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007129 switch(event) {
7130 case STARTING_OUTPUT:
7131 mBeaconMuteRefCount++;
7132 break;
7133 case STOPPING_OUTPUT:
7134 if (mBeaconMuteRefCount > 0) {
7135 mBeaconMuteRefCount--;
7136 }
7137 break;
7138 case STARTING_BEACON:
7139 mBeaconPlayingRefCount++;
7140 break;
7141 case STOPPING_BEACON:
7142 if (mBeaconPlayingRefCount > 0) {
7143 mBeaconPlayingRefCount--;
7144 }
7145 break;
7146 }
7147
7148 if (mBeaconMuteRefCount > 0) {
7149 // any playback causes beacon to be muted
7150 return setBeaconMute(true);
7151 } else {
7152 // no other playback: unmute when beacon starts playing, mute when it stops
7153 return setBeaconMute(mBeaconPlayingRefCount == 0);
7154 }
7155}
7156
7157uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7158 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7159 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7160 // keep track of muted state to avoid repeating mute/unmute operations
7161 if (mBeaconMuted != mute) {
7162 // mute/unmute AUDIO_STREAM_TTS on all outputs
7163 ALOGV("\t muting %d", mute);
7164 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007165 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7166 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7167 ALOGV("\t no tts volume source available");
7168 return 0;
7169 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007170 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007171 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007172 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007173 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007174 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007175 maxLatency = latency;
7176 }
7177 }
7178 mBeaconMuted = mute;
7179 return maxLatency;
7180 }
7181 return 0;
7182}
7183
Eric Laurente0720872014-03-11 09:30:41 -07007184void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007185{
François Gaffiec005e562018-11-06 15:04:49 +01007186 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007187 mPreviousOutputs = mOutputs;
7188}
7189
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007190uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007191 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007192 uint32_t delayMs)
7193{
7194 // mute/unmute strategies using an incompatible device combination
7195 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7196 // if unmuting, unmute only after the specified delay
7197 if (outputDesc->isDuplicated()) {
7198 return 0;
7199 }
7200
7201 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007202 DeviceVector devices = outputDesc->devices();
7203 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007204
François Gaffiec005e562018-11-06 15:04:49 +01007205 auto productStrategies = mEngine->getOrderedProductStrategies();
7206 for (const auto &productStrategy : productStrategies) {
7207 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7208 DeviceVector curDevices =
7209 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7210 curDevices = curDevices.filter(outputDesc->supportedDevices());
7211 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007212 bool doMute = false;
7213
François Gaffiec005e562018-11-06 15:04:49 +01007214 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007215 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007216 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7217 } else 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, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007220 }
Eric Laurent99401132014-05-07 19:48:15 -07007221 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007222 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007223 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007224 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007225 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007226 continue;
7227 }
François Gaffiec005e562018-11-06 15:04:49 +01007228 ALOGVV("%s() %s (curDevice %s)", __func__,
7229 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7230 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7231 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007232 if (mute) {
7233 // FIXME: should not need to double latency if volume could be applied
7234 // immediately by the audioflinger mixer. We must account for the delay
7235 // between now and the next time the audioflinger thread for this output
7236 // will process a buffer (which corresponds to one buffer size,
7237 // usually 1/2 or 1/4 of the latency).
7238 if (muteWaitMs < desc->latency() * 2) {
7239 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007240 }
7241 }
7242 }
7243 }
7244 }
7245 }
7246
Eric Laurent99401132014-05-07 19:48:15 -07007247 // temporary mute output if device selection changes to avoid volume bursts due to
7248 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007249 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007250 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007251
Eric Laurentdc462862016-07-19 12:29:53 -07007252 if (muteWaitMs < tempMuteWaitMs) {
7253 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007254 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007255
7256 // If recommended duration is defined, replace temporary mute duration to avoid
7257 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7258 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7259 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7260 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7261 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7262
François Gaffieaaac0fd2018-11-22 17:56:39 +01007263 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7264 // make sure that we do not start the temporary mute period too early in case of
7265 // delayed device change
7266 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7267 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007268 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007269 }
7270 }
7271
Eric Laurente552edb2014-03-10 17:42:56 -07007272 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7273 if (muteWaitMs > delayMs) {
7274 muteWaitMs -= delayMs;
7275 usleep(muteWaitMs * 1000);
7276 return muteWaitMs;
7277 }
7278 return 0;
7279}
7280
François Gaffie11d30102018-11-02 16:09:09 +01007281uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7282 const DeviceVector &devices,
7283 bool force,
7284 int delayMs,
7285 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02007286 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07007287{
jiabin3ff8d7d2022-12-13 06:27:44 +00007288 // TODO(b/262404095): Consider if the output need to be reopened.
François Gaffie11d30102018-11-02 16:09:09 +01007289 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007290 uint32_t muteWaitMs;
7291
7292 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01007293 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
7294 nullptr /* patchHandle */, requiresMuteCheck);
7295 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
7296 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07007297 return muteWaitMs;
7298 }
Eric Laurente552edb2014-03-10 17:42:56 -07007299
7300 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007301 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007302 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007303 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007304
François Gaffie11d30102018-11-02 16:09:09 +01007305 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7306
7307 if (!filteredDevices.isEmpty()) {
7308 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007309 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007310
7311 // if the outputs are not materially active, there is no need to mute.
7312 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007313 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007314 } else {
7315 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7316 muteWaitMs = 0;
7317 }
Eric Laurente552edb2014-03-10 17:42:56 -07007318
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007319 bool outputRouted = outputDesc->isRouted();
7320
Eric Laurent79ea9582020-06-11 18:49:24 -07007321 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7322 // output profile or if new device is not supported AND previous device(s) is(are) still
7323 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007324 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007325 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7326 // restore previous device after evaluating strategy mute state
7327 outputDesc->setDevices(prevDevices);
7328 return muteWaitMs;
7329 }
7330
Eric Laurente552edb2014-03-10 17:42:56 -07007331 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007332 // the requested device is AUDIO_DEVICE_NONE
7333 // OR the requested device is the same as current device
7334 // AND force is not specified
7335 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007336 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007337 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007338 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7339 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007340 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7341 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7342 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7343 }
Eric Laurente552edb2014-03-10 17:42:56 -07007344 return muteWaitMs;
7345 }
7346
François Gaffie11d30102018-11-02 16:09:09 +01007347 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007348
Eric Laurente552edb2014-03-10 17:42:56 -07007349 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007350 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007351 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007352 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007353 PatchBuilder patchBuilder;
7354 patchBuilder.addSource(outputDesc);
7355 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7356 for (const auto &filteredDevice : filteredDevices) {
7357 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007358 }
7359
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007360 // Add half reported latency to delayMs when muteWaitMs is null in order
7361 // to avoid disordered sequence of muting volume and changing devices.
7362 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7363 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007364 }
Eric Laurente552edb2014-03-10 17:42:56 -07007365
7366 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007367 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007368
7369 return muteWaitMs;
7370}
7371
Eric Laurentc75307b2015-03-17 15:29:32 -07007372status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007373 int delayMs,
7374 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007375{
Eric Laurent6a94d692014-05-20 11:18:06 -07007376 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007377 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7378 return INVALID_OPERATION;
7379 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007380 if (patchHandle) {
7381 index = mAudioPatches.indexOfKey(*patchHandle);
7382 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007383 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007384 }
7385 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007386 return INVALID_OPERATION;
7387 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007388 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007389 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007390 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007391 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007392 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007393 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007394 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007395 return status;
7396}
7397
7398status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007399 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007400 bool force,
7401 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007402{
7403 status_t status = NO_ERROR;
7404
Eric Laurent1f2f2232014-06-02 12:01:23 -07007405 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007406 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7407 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007408
François Gaffie11d30102018-11-02 16:09:09 +01007409 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007410 PatchBuilder patchBuilder;
7411 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007412 // AUDIO_SOURCE_HOTWORD is for internal use only:
7413 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007414 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7415 auto result = usecase;
7416 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7417 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7418 }
7419 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007420 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007421 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007422 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007423 }
7424 }
7425 return status;
7426}
7427
Eric Laurent6a94d692014-05-20 11:18:06 -07007428status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7429 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007430{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007431 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007432 ssize_t index;
7433 if (patchHandle) {
7434 index = mAudioPatches.indexOfKey(*patchHandle);
7435 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007436 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007437 }
7438 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007439 return INVALID_OPERATION;
7440 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007441 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007442 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007443 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007444 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007445 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007446 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007447 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007448 return status;
7449}
7450
François Gaffie11d30102018-11-02 16:09:09 +01007451sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007452 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007453 audio_format_t& format,
7454 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007455 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007456{
7457 // Choose an input profile based on the requested capture parameters: select the first available
7458 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007459 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007460 //
7461 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7462 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007463
Atneya Nair0f0a8032022-12-12 16:20:12 -08007464 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7465 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7466 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7467
7468 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007469
jiabin2fd710d2022-05-02 23:20:22 +00007470 for (;;) {
7471 sp<IOProfile> firstInexact = nullptr;
7472 uint32_t updatedSamplingRate = 0;
7473 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7474 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7475 for (const auto& hwModule : mHwModules) {
7476 for (const auto& profile : hwModule->getInputProfiles()) {
7477 // profile->log();
7478 //updatedFormat = format;
7479 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7480 &samplingRate /*updatedSamplingRate*/,
7481 format,
7482 &format, /*updatedFormat*/
7483 channelMask,
7484 &channelMask /*updatedChannelMask*/,
7485 // FIXME ugly cast
7486 (audio_output_flags_t) flags,
7487 true /*exactMatchRequiredForInputFlags*/)) {
7488 return profile;
7489 }
7490 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7491 samplingRate,
7492 &updatedSamplingRate,
7493 format,
7494 &updatedFormat,
7495 channelMask,
7496 &updatedChannelMask,
7497 // FIXME ugly cast
7498 (audio_output_flags_t) flags,
7499 false /*exactMatchRequiredForInputFlags*/)) {
7500 firstInexact = profile;
7501 }
7502 }
7503 }
7504
7505 if (firstInexact != nullptr) {
7506 samplingRate = updatedSamplingRate;
7507 format = updatedFormat;
7508 channelMask = updatedChannelMask;
7509 return firstInexact;
7510 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7511 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7512 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7513 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7514 flags = AUDIO_INPUT_FLAG_NONE;
7515 } else { // fail
7516 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7517 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7518 samplingRate, format, channelMask, oriFlags);
7519 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007520 }
7521 }
jiabin2fd710d2022-05-02 23:20:22 +00007522
7523 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007524}
7525
François Gaffieaaac0fd2018-11-22 17:56:39 +01007526float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7527 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007528 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007529 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007530{
jiabin9a3361e2019-10-01 09:38:30 -07007531 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007532
7533 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7534 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7535 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7536 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007537 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7538 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7539 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7540 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7541 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007542
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007543 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007544 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7545 mOutputs.isActive(ringVolumeSrc, 0)) {
7546 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007547 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007548 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007549 }
7550
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007551 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007552 if ((volumeSource != callVolumeSrc && (isInCall() ||
7553 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007554 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007555 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7556 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007557 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7558 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7559 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007560 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007561 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007562 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007563 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007564 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007565 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007566 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7567 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7568 // programmatically muted.
7569 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7570 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7571 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007572 bool exemptFromCapping =
7573 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7574 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007575 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7576 volumeSource, volumeDb);
7577 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007578 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7579 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7580 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007581 }
7582 }
Eric Laurente552edb2014-03-10 17:42:56 -07007583 // if a headset is connected, apply the following rules to ring tones and notifications
7584 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007585 // - always attenuate notifications volume by 6dB
7586 // - attenuate ring tones volume by 6dB unless music is not playing and
7587 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007588 // - if music is playing, always limit the volume to current music volume,
7589 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007590 if (!Intersection(deviceTypes,
7591 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7592 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007593 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7594 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007595 ((volumeSource == alarmVolumeSrc ||
7596 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007597 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7598 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7599 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007600 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7601 curves.canBeMuted()) {
7602
Eric Laurente552edb2014-03-10 17:42:56 -07007603 // when the phone is ringing we must consider that music could have been paused just before
7604 // by the music application and behave as if music was active if the last music track was
7605 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007606 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007607 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007608 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007609 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007610 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7611 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007612 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007613 float musicVolDb = computeVolume(musicCurves,
7614 musicVolumeSrc,
7615 musicCurves.getVolumeIndex(musicDevice),
7616 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007617 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7618 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7619 if (volumeDb > minVolDb) {
7620 volumeDb = minVolDb;
7621 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007622 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007623 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7624 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7625 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007626 // on A2DP, also ensure notification volume is not too low compared to media when
7627 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007628 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007629 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007630 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7631 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007632 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7633 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007634 }
7635 }
jiabin9a3361e2019-10-01 09:38:30 -07007636 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007637 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007638 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007639 }
7640 }
7641
François Gaffie43c73442018-11-08 08:21:55 +01007642 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007643}
7644
Eric Laurent3839bc02018-07-10 18:33:34 -07007645int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007646 VolumeSource fromVolumeSource,
7647 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007648{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007649 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007650 return srcIndex;
7651 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007652 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7653 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007654 float minSrc = (float)srcCurves.getVolumeIndexMin();
7655 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7656 float minDst = (float)dstCurves.getVolumeIndexMin();
7657 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007658
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007659 // preserve mute request or correct range
7660 if (srcIndex < minSrc) {
7661 if (srcIndex == 0) {
7662 return 0;
7663 }
7664 srcIndex = minSrc;
7665 } else if (srcIndex > maxSrc) {
7666 srcIndex = maxSrc;
7667 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007668 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7669}
7670
François Gaffieaaac0fd2018-11-22 17:56:39 +01007671status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7672 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007673 int index,
7674 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007675 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007676 int delayMs,
7677 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007678{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007679 // do not change actual attributes volume if the attributes is muted
7680 if (outputDesc->isMuted(volumeSource)) {
7681 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7682 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007683 return NO_ERROR;
7684 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007685 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7686 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7687 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7688 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007689
Eric Laurent2517af32020-11-25 15:31:27 +01007690 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007691 bool isHAUsed = isHearingAidUsedForComm();
7692
Eric Laurente552edb2014-03-10 17:42:56 -07007693 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007694 // if sco and call follow same curves, bypass forceUseForComm
7695 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007696 ((isVoiceVolSrc && isScoRequested) ||
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007697 (isBtScoVolSrc && !(isScoRequested || isHAUsed)))) {
Eric Laurent2517af32020-11-25 15:31:27 +01007698 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007699 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007700 // Do not return an error here as AudioService will always set both voice call
7701 // and bluetooth SCO volumes due to stream aliasing.
7702 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007703 }
jiabin9a3361e2019-10-01 09:38:30 -07007704 if (deviceTypes.empty()) {
7705 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007706 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007707
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007708 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7709 ALOGE("invalid volume index range");
7710 return BAD_VALUE;
7711 }
7712
jiabin9a3361e2019-10-01 09:38:30 -07007713 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7714 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007715 // Force VoIP volume to max for bluetooth SCO device except if muted
7716 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007717 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007718 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007719 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007720 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007721 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007722 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007723
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007724 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007725 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007726 // 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 +01007727 if (isVoiceVolSrc) {
7728 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007729 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007730 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007731 }
Eric Laurent18fba842016-03-31 14:41:26 -07007732 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007733 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7734 mLastVoiceVolume = voiceVolume;
7735 }
7736 }
Eric Laurente552edb2014-03-10 17:42:56 -07007737 return NO_ERROR;
7738}
7739
Eric Laurentc75307b2015-03-17 15:29:32 -07007740void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007741 const DeviceTypeSet& deviceTypes,
7742 int delayMs,
7743 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007744{
jiabincd510522020-01-22 09:40:55 -08007745 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007746 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7747 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7748 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007749 curves.getVolumeIndex(deviceTypes),
7750 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007751 }
7752}
7753
François Gaffiec005e562018-11-06 15:04:49 +01007754void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7755 bool on,
7756 const sp<AudioOutputDescriptor>& outputDesc,
7757 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007758 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007759{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007760 std::vector<VolumeSource> sourcesToMute;
7761 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7762 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7763 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007764 VolumeSource source = toVolumeSource(attributes, false);
7765 if ((source != VOLUME_SOURCE_NONE) &&
7766 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7767 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007768 sourcesToMute.push_back(source);
7769 }
Eric Laurente552edb2014-03-10 17:42:56 -07007770 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007771 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007772 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007773 }
7774
Eric Laurente552edb2014-03-10 17:42:56 -07007775}
7776
François Gaffieaaac0fd2018-11-22 17:56:39 +01007777void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7778 bool on,
7779 const sp<AudioOutputDescriptor>& outputDesc,
7780 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007781 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007782{
jiabin9a3361e2019-10-01 09:38:30 -07007783 if (deviceTypes.empty()) {
7784 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007785 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007786 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007787 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007788 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007789 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007790 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007791 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7792 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007793 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007794 }
7795 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007796 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7797 // ignored
7798 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007799 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007800 if (!outputDesc->isMuted(volumeSource)) {
7801 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007802 return;
7803 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007804 if (outputDesc->decMuteCount(volumeSource) == 0) {
7805 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007806 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007807 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007808 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007809 delayMs);
7810 }
7811 }
7812}
7813
François Gaffie53615e22015-03-19 09:24:12 +01007814bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7815{
François Gaffiec005e562018-11-06 15:04:49 +01007816 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007817 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7818 return true;
7819 }
7820
7821 // has known usage?
7822 switch (paa->usage) {
7823 case AUDIO_USAGE_UNKNOWN:
7824 case AUDIO_USAGE_MEDIA:
7825 case AUDIO_USAGE_VOICE_COMMUNICATION:
7826 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7827 case AUDIO_USAGE_ALARM:
7828 case AUDIO_USAGE_NOTIFICATION:
7829 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7830 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7831 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7832 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7833 case AUDIO_USAGE_NOTIFICATION_EVENT:
7834 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7835 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7836 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7837 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007838 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007839 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007840 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007841 case AUDIO_USAGE_EMERGENCY:
7842 case AUDIO_USAGE_SAFETY:
7843 case AUDIO_USAGE_VEHICLE_STATUS:
7844 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007845 break;
7846 default:
7847 return false;
7848 }
7849 return true;
7850}
7851
François Gaffie2110e042015-03-24 08:41:51 +01007852audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7853{
7854 return mEngine->getForceUse(usage);
7855}
7856
Eric Laurent96d1dda2022-03-14 17:14:19 +01007857bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007858 return isStateInCall(mEngine->getPhoneState());
7859}
7860
Eric Laurent96d1dda2022-03-14 17:14:19 +01007861bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007862 return is_state_in_call(state);
7863}
7864
Eric Laurentf9cccec2022-11-16 19:12:00 +01007865bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007866 audio_mode_t mode = mEngine->getPhoneState();
7867 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007868 || (mode == AUDIO_MODE_CALL_SCREEN)
7869 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007870}
7871
Eric Laurentf9cccec2022-11-16 19:12:00 +01007872bool AudioPolicyManager::isInCallOrScreening() const {
7873 audio_mode_t mode = mEngine->getPhoneState();
7874 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7875}
7876
Eric Laurentd60560a2015-04-10 11:31:20 -07007877void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7878{
7879 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007880 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007881 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007882 sourceDesc->sinkDevice()->equals(deviceDesc))
7883 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007884 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007885 }
7886 }
7887
7888 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7889 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7890 bool release = false;
7891 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7892 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7893 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7894 source->ext.device.type == deviceDesc->type()) {
7895 release = true;
7896 }
7897 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007898 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007899 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7900 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7901 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007902 sink->ext.device.type == deviceDesc->type() &&
7903 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7904 || strncmp(sink->ext.device.address, address,
7905 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007906 release = true;
7907 }
7908 }
7909 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007910 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7911 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007912 }
7913 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007914
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007915 mInputs.clearSessionRoutesForDevice(deviceDesc);
7916
Francois Gaffie716e1432019-01-14 16:58:59 +01007917 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007918}
7919
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007920void AudioPolicyManager::modifySurroundFormats(
7921 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007922 std::unordered_set<audio_format_t> enforcedSurround(
7923 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007924 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7925 for (const auto& pair : mConfig.getSurroundFormats()) {
7926 allSurround.insert(pair.first);
7927 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7928 }
Phil Burk09bc4612016-02-24 15:58:15 -08007929
7930 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7931 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007932 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007933 // This is the resulting set of formats depending on the surround mode:
7934 // 'all surround' = allSurround
7935 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7936 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7937 // 'manual surround' = mManualSurroundFormats
7938 // AUTO: formats v 'enforced surround'
7939 // ALWAYS: formats v 'all surround' v 'enforced surround'
7940 // NEVER: formats ^ 'non-surround'
7941 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007942
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007943 std::unordered_set<audio_format_t> formatSet;
7944 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7945 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007946 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007947 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007948 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007949 formatSet.insert(*formatIter);
7950 }
7951 }
7952 } else {
7953 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7954 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007955 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007956
jiabin81772902018-04-02 17:52:27 -07007957 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007958 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007959 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7960 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7961 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007962 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007963 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7964 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7965 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007966 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007967 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007968 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007969 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007970 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007971 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007972}
7973
jiabin06e4bab2019-07-29 10:13:34 -07007974void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7975 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007976 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7977 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7978
7979 // If NEVER, then remove support for channelMasks > stereo.
7980 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007981 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7982 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007983 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007984 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007985 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007986 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007987 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007988 }
7989 }
jiabin81772902018-04-02 17:52:27 -07007990 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7991 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7992 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007993 bool supports5dot1 = false;
7994 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007995 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007996 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7997 supports5dot1 = true;
7998 break;
7999 }
8000 }
8001 // If not then add 5.1 support.
8002 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008003 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008004 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008005 }
Phil Burk09bc4612016-02-24 15:58:15 -08008006 }
8007}
8008
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008009void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008010 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01008011 AudioProfileVector &profiles)
8012{
8013 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008014 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07008015
François Gaffie112b0af2015-11-19 16:13:25 +01008016 // Format MUST be checked first to update the list of AudioProfile
8017 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008018 reply = mpClientInterface->getParameters(
8019 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07008020 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008021 AudioParameter repliedParameters(reply);
8022 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008023 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01008024 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
8025 return;
8026 }
Phil Burk09bc4612016-02-24 15:58:15 -08008027 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01008028 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08008029 if (device == AUDIO_DEVICE_OUT_HDMI
8030 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008031 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07008032 }
jiabin3e277cc2019-09-10 14:27:34 -07008033 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01008034 }
François Gaffie112b0af2015-11-19 16:13:25 +01008035
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008036 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07008037 ChannelMaskSet channelMasks;
8038 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01008039 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07008040 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01008041
8042 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008043 reply = mpClientInterface->getParameters(
8044 ioHandle,
8045 requestedParameters.toString() + ";" +
8046 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01008047 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008048 AudioParameter repliedParameters(reply);
8049 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008050 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008051 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01008052 }
8053 }
8054 if (profiles.hasDynamicChannelsFor(format)) {
8055 reply = mpClientInterface->getParameters(ioHandle,
8056 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07008057 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01008058 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008059 AudioParameter repliedParameters(reply);
8060 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008061 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008062 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008063 if (device == AUDIO_DEVICE_OUT_HDMI
8064 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008065 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07008066 }
François Gaffie112b0af2015-11-19 16:13:25 +01008067 }
8068 }
jiabin3e277cc2019-09-10 14:27:34 -07008069 addDynamicAudioProfileAndSort(
8070 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01008071 }
8072}
Eric Laurentd60560a2015-04-10 11:31:20 -07008073
Mikhail Naganovdc769682018-05-04 15:34:08 -07008074status_t AudioPolicyManager::installPatch(const char *caller,
8075 audio_patch_handle_t *patchHandle,
8076 AudioIODescriptorInterface *ioDescriptor,
8077 const struct audio_patch *patch,
8078 int delayMs)
8079{
8080 ssize_t index = mAudioPatches.indexOfKey(
8081 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8082 *patchHandle : ioDescriptor->getPatchHandle());
8083 sp<AudioPatch> patchDesc;
8084 status_t status = installPatch(
8085 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8086 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008087 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008088 }
8089 return status;
8090}
8091
8092status_t AudioPolicyManager::installPatch(const char *caller,
8093 ssize_t index,
8094 audio_patch_handle_t *patchHandle,
8095 const struct audio_patch *patch,
8096 int delayMs,
8097 uid_t uid,
8098 sp<AudioPatch> *patchDescPtr)
8099{
8100 sp<AudioPatch> patchDesc;
8101 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8102 if (index >= 0) {
8103 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008104 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008105 }
8106
8107 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8108 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8109 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8110 if (status == NO_ERROR) {
8111 if (index < 0) {
8112 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008113 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008114 } else {
8115 patchDesc->mPatch = *patch;
8116 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008117 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008118 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008119 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008120 }
8121 nextAudioPortGeneration();
8122 mpClientInterface->onAudioPatchListUpdate();
8123 }
8124 if (patchDescPtr) *patchDescPtr = patchDesc;
8125 return status;
8126}
8127
jiabinbce0c1d2020-10-05 11:20:18 -07008128bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8129{
8130 const TrackClientVector activeClients = output->getActiveClients();
8131 if (activeClients.empty()) {
8132 return true;
8133 }
8134 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8135 if (index < 0) {
8136 ALOGE("%s, no audio patch found while there are active clients on output %d",
8137 __func__, output->getId());
8138 return false;
8139 }
8140 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8141 DeviceVector routedDevices;
8142 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8143 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8144 patchDesc->mPatch.sinks[i].id);
8145 if (device == nullptr) {
8146 ALOGE("%s, no audio device found with id(%d)",
8147 __func__, patchDesc->mPatch.sinks[i].id);
8148 return false;
8149 }
8150 routedDevices.add(device);
8151 }
8152 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008153 if (client->isInvalid()) {
8154 // No need to take care about invalidated clients.
8155 continue;
8156 }
jiabinbce0c1d2020-10-05 11:20:18 -07008157 sp<DeviceDescriptor> preferredDevice =
8158 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8159 if (mEngine->getOutputDevicesForAttributes(
8160 client->attributes(), preferredDevice, false) == routedDevices) {
8161 return false;
8162 }
8163 }
8164 return true;
8165}
8166
8167sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008168 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008169 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8170 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008171{
8172 for (const auto& device : devices) {
8173 // TODO: This should be checking if the profile supports the device combo.
8174 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008175 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8176 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008177 return nullptr;
8178 }
8179 }
8180 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8181 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008182 status_t status = desc->open(halConfig, mixerConfig, devices,
8183 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008184 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008185 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008186 return nullptr;
8187 }
8188
8189 // Here is where the out_set_parameters() for card & device gets called
8190 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8191 const audio_devices_t deviceType = device->type();
8192 const String8 &address = String8(device->address().c_str());
8193 if (!address.isEmpty()) {
8194 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8195 mpClientInterface->setParameters(output, String8(param));
8196 free(param);
8197 }
8198 updateAudioProfiles(device, output, profile->getAudioProfiles());
8199 if (!profile->hasValidAudioProfile()) {
8200 ALOGW("%s() missing param", __func__);
8201 desc->close();
8202 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008203 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8204 // Reopen the output with the best audio profile picked by APM when the profile supports
8205 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008206 desc->close();
8207 output = AUDIO_IO_HANDLE_NONE;
8208 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8209 profile->pickAudioProfile(
8210 config.sample_rate, config.channel_mask, config.format);
8211 config.offload_info.sample_rate = config.sample_rate;
8212 config.offload_info.channel_mask = config.channel_mask;
8213 config.offload_info.format = config.format;
8214
jiabina84c3d32022-12-02 18:59:55 +00008215 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008216 if (status != NO_ERROR) {
8217 return nullptr;
8218 }
8219 }
8220
8221 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008222
baek.kim -61c20122022-07-27 10:05:32 +00008223 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8224 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8225
jiabinbce0c1d2020-10-05 11:20:18 -07008226 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8227 sp<AudioPolicyMix> policyMix;
8228 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8229 policyMix->setOutput(desc);
8230 desc->mPolicyMix = policyMix;
8231 } else {
8232 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
8233 address.string());
8234 }
8235
baek.kim -61c20122022-07-27 10:05:32 +00008236 } else if (hasPrimaryOutput() && speaker != nullptr
8237 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008238 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8239 // no duplicated output for:
8240 // - direct outputs
8241 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008242 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008243 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8244
8245 //TODO: configure audio effect output stage here
8246
8247 // open a duplicating output thread for the new output and the primary output
8248 sp<SwAudioOutputDescriptor> dupOutputDesc =
8249 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8250 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8251 if (status == NO_ERROR) {
8252 // add duplicated output descriptor
8253 addOutput(duplicatedOutput, dupOutputDesc);
8254 } else {
8255 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8256 mPrimaryOutput->mIoHandle, output);
8257 desc->close();
8258 removeOutput(output);
8259 nextAudioPortGeneration();
8260 return nullptr;
8261 }
8262 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008263 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8264 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8265 mPrimaryOutput = desc;
8266 }
jiabinbce0c1d2020-10-05 11:20:18 -07008267 return desc;
8268}
8269
jiabinf1c73972022-04-14 16:28:52 -07008270status_t AudioPolicyManager::getDevicesForAttributes(
8271 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8272 // Devices are determined in the following precedence:
8273 //
8274 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8275 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8276 //
8277 // If no such dynamic policy then
8278 // 2) Devices containing an active client using setPreferredDevice
8279 // with same strategy as the attributes.
8280 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8281 //
8282 // If no corresponding active client with setPreferredDevice then
8283 // 3) Devices associated with the strategy determined by the attributes
8284 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8285 //
8286 // See related getOutputForAttrInt().
8287
8288 // check dynamic policies but only for primary descriptors (secondary not used for audible
8289 // audio routing, only used for duplication for playback capture)
8290 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008291 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008292 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008293 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8294 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8295 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008296 if (status != OK) {
8297 return status;
8298 }
8299
8300 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8301 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8302 // as they are unaffected by device/stream volume
8303 // (per SwAudioOutputDescriptor::isFixedVolume()).
8304 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8305 ) {
8306 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8307 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8308 devices.add(deviceDesc);
8309 } else {
8310 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8311 // which selects setPreferredDevice if active. This means forVolume call
8312 // will take an active setPreferredDevice, if such exists.
8313
8314 devices = mEngine->getOutputDevicesForAttributes(
8315 attr, nullptr /* preferredDevice */, false /* fromCache */);
8316 }
8317
8318 if (forVolume) {
8319 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8320 // for single volume control in AudioService (such relationship should exist if
8321 // SPEAKER_SAFE is present).
8322 //
8323 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8324 DeviceVector speakerSafeDevices =
8325 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8326 if (!speakerSafeDevices.isEmpty()) {
8327 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8328 devices.remove(speakerSafeDevices);
8329 }
8330 }
8331
8332 return NO_ERROR;
8333}
8334
8335status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8336 AudioProfileVector& audioProfiles,
8337 uint32_t flags,
8338 bool isInput) {
8339 for (const auto& hwModule : mHwModules) {
8340 // the MSD module checks for different conditions
8341 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8342 continue;
8343 }
8344 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8345 : hwModule->getOutputProfiles();
8346 for (const auto& profile : ioProfiles) {
8347 if (!profile->areAllDevicesSupported(devices) ||
8348 !profile->isCompatibleProfileForFlags(
8349 flags, false /*exactMatchRequiredForInputFlags*/)) {
8350 continue;
8351 }
8352 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8353 }
8354 }
8355
8356 if (!isInput) {
8357 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8358 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8359 if (msdModule != nullptr) {
8360 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8361 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8362 for (const auto &profile: msdModule->getOutputProfiles()) {
8363 if (!profile->asAudioPort()->isDirectOutput()) {
8364 continue;
8365 }
8366 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8367 }
8368 } else {
8369 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8370 }
8371 }
8372 }
8373
8374 return NO_ERROR;
8375}
8376
jiabin3ff8d7d2022-12-13 06:27:44 +00008377sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8378 const audio_config_t *config,
8379 audio_output_flags_t flags,
8380 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008381 closeOutput(outputDesc->mIoHandle);
8382 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8383 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8384 if (preferredOutput == nullptr) {
8385 ALOGE("%s failed to reopen output device=%d, caller=%s",
8386 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008387 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008388 return preferredOutput;
8389}
8390
8391void AudioPolicyManager::reopenOutputsWithDevices(
8392 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8393 for (const auto& [output, devices] : outputsToReopen) {
8394 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8395 closeOutput(output);
8396 openOutputWithProfileAndDevice(desc->mProfile, devices);
8397 }
jiabina84c3d32022-12-02 18:59:55 +00008398}
8399
jiabinc44b3462022-12-08 12:52:31 -08008400PortHandleVector AudioPolicyManager::getClientsForStream(
8401 audio_stream_type_t streamType) const {
8402 PortHandleVector clients;
8403 for (size_t i = 0; i < mOutputs.size(); ++i) {
8404 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8405 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8406 }
8407 return clients;
8408}
8409
8410void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8411 PortHandleVector clients;
8412 for (auto stream : streams) {
8413 PortHandleVector clientsForStream = getClientsForStream(stream);
8414 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8415 }
8416 mpClientInterface->invalidateTracks(clients);
8417}
8418
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008419} // namespace android