blob: a3f2e597fefe51e7d3822273133a4109eddfbd17 [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>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080037#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110038#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070039
40#include <Serializer.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070041#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070042#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070043#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070044#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070045#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070046#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070047#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070048#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070049#include <utils/Log.h>
50
Eric Laurentd4692962014-05-05 18:13:44 -070051#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010052#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070053
Eric Laurent3b73df72014-03-11 09:06:29 -070054namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070055
Svet Ganov3e5f14f2021-05-13 22:51:08 +000056using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070057
Eric Laurentdc462862016-07-19 12:29:53 -070058//FIXME: workaround for truncated touch sounds
59// to be removed when the problem is handled by system UI
60#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070061
62// Largest difference in dB on earpiece in call between the voice volume and another
63// media / notification / system volume.
64constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
65
Mikhail Naganov15be9d22017-11-08 14:18:13 +110066// Compressed formats for MSD module, ordered from most preferred to least preferred.
Dean Wheatley8bee85a2021-02-10 16:02:23 +110067static const std::vector<audio_format_t> msdCompressedFormatsOrder = {{
68 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Mikhail Naganov15be9d22017-11-08 14:18:13 +110069 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
70// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
Dean Wheatley8bee85a2021-02-10 16:02:23 +110071static const std::vector<audio_channel_mask_t> msdSurroundChannelMasksOrder = {{
Mikhail Naganov15be9d22017-11-08 14:18:13 +110072 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
73 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
74 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
75
jiabin06e4bab2019-07-29 10:13:34 -070076template <typename T>
77bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
78{
79 if (left.size() != right.size()) {
80 return false;
81 }
82 for (size_t index = 0; index < right.size(); index++) {
83 if (left[index] != right[index]) {
84 return false;
85 }
86 }
87 return true;
88}
89
90template <typename T>
91bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
92{
93 return !(left == right);
94}
95
Eric Laurente552edb2014-03-10 17:42:56 -070096// ----------------------------------------------------------------------------
97// AudioPolicyInterface implementation
98// ----------------------------------------------------------------------------
99
Eric Laurente0720872014-03-11 09:30:41 -0700100status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -0800101 audio_policy_dev_state_t state,
102 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800103 const char *device_name,
104 audio_format_t encodedFormat)
Eric Laurente552edb2014-03-10 17:42:56 -0700105{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800106 status_t status = setDeviceConnectionStateInt(device, state, device_address,
107 device_name, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800108 nextAudioPortGeneration();
109 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800110}
111
François Gaffie11d30102018-11-02 16:09:09 +0100112void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
113 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200114{
jiabince9f20e2019-09-12 16:29:15 -0700115 AudioParameter param(String8(device->address().c_str()));
François Gaffie44481e72016-04-20 07:49:57 +0200116 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganovf23fcf62019-07-08 15:28:43 -0700117 AudioParameter::keyDeviceConnect : AudioParameter::keyDeviceDisconnect);
François Gaffie11d30102018-11-02 16:09:09 +0100118 param.addInt(key, device->type());
François Gaffie44481e72016-04-20 07:49:57 +0200119 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
120}
121
François Gaffie11d30102018-11-02 16:09:09 +0100122status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800123 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800124 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800125 const char *device_name,
126 audio_format_t encodedFormat)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800127{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800128 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s format 0x%X",
129 deviceType, state, device_address, device_name, encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700130
131 // connect/disconnect only 1 device at a time
François Gaffie11d30102018-11-02 16:09:09 +0100132 if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -0700133
François Gaffie11d30102018-11-02 16:09:09 +0100134 sp<DeviceDescriptor> device =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800135 mHwModules.getDeviceDescriptor(deviceType, device_address, device_name, encodedFormat,
Francois Gaffie716e1432019-01-14 16:58:59 +0100136 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700137 return device ? setDeviceConnectionStateInt(device, state) : INVALID_OPERATION;
138}
Paul McLeane743a472015-01-28 11:07:31 -0800139
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700140status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
141 audio_policy_dev_state_t state)
142{
Eric Laurente552edb2014-03-10 17:42:56 -0700143 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700144 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700145 SortedVector <audio_io_handle_t> outputs;
146
François Gaffie11d30102018-11-02 16:09:09 +0100147 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700148
Eric Laurente552edb2014-03-10 17:42:56 -0700149 // save a copy of the opened output descriptors before any output is opened or closed
150 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
151 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700152 switch (state)
153 {
154 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800155 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700156 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100157 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700158 return INVALID_OPERATION;
159 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800160 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700161 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700162
Eric Laurente552edb2014-03-10 17:42:56 -0700163 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200164 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700165 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700166 }
167
François Gaffie44481e72016-04-20 07:49:57 +0200168 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
169 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100170 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200171
François Gaffie11d30102018-11-02 16:09:09 +0100172 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
173 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200174
Francois Gaffie716e1432019-01-14 16:58:59 +0100175 mHwModules.cleanUpForDevice(device);
176
François Gaffie11d30102018-11-02 16:09:09 +0100177 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700178 return INVALID_OPERATION;
179 }
François Gaffie2110e042015-03-24 08:41:51 +0100180
jiabin1c4794b2020-05-05 10:08:05 -0700181 // Populate encapsulation information when a output device is connected.
182 device->setEncapsulationInfoFromHal(mpClientInterface);
183
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700184 // outputs should never be empty here
185 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
186 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100187 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800188
Eric Laurent3ae5f312015-02-03 17:12:08 -0800189 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700190 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700191 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700192 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100193 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700194 return INVALID_OPERATION;
195 }
196
François Gaffie11d30102018-11-02 16:09:09 +0100197 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700198
Paul McLeane743a472015-01-28 11:07:31 -0800199 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100200 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700201
Eric Laurente552edb2014-03-10 17:42:56 -0700202 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100203 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700204
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100205 mOutputs.clearSessionRoutesForDevice(device);
206
François Gaffie11d30102018-11-02 16:09:09 +0100207 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100208
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800209 // Reset active device codec
210 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
211
Kriti Dangef6be8f2020-11-05 11:58:19 +0100212 // remove device from mReportedFormatsMap cache
213 mReportedFormatsMap.erase(device);
214
Eric Laurente552edb2014-03-10 17:42:56 -0700215 } break;
216
217 default:
François Gaffie11d30102018-11-02 16:09:09 +0100218 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700219 return BAD_VALUE;
220 }
221
Eric Laurent736a1022019-03-27 18:28:46 -0700222 // Propagate device availability to Engine
223 setEngineDeviceConnectionState(device, state);
224
Eric Laurentae970022019-01-29 14:25:04 -0800225 // No need to evaluate playback routing when connecting a remote submix
226 // output device used by a dynamic policy of type recorder as no
227 // playback use case is affected.
228 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700229 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800230 for (audio_io_handle_t output : outputs) {
231 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800232 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
233 if (policyMix != nullptr
234 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700235 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800236 doCheckForDeviceAndOutputChanges = false;
237 break;
238 }
239 }
240 }
241
242 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700243 // outputs must be closed after checkOutputForAllStrategies() is executed
244 if (!outputs.isEmpty()) {
245 for (audio_io_handle_t output : outputs) {
246 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100247 // close unused outputs after device disconnection or direct outputs that have
248 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200249 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
250 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurent39095982021-08-24 18:29:27 +0200251 (desc->mDirectOpenCount == 0))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200252 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700253 closeOutput(output);
254 }
Eric Laurente552edb2014-03-10 17:42:56 -0700255 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700256 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
257 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700258 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700259 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800260 };
261
262 if (doCheckForDeviceAndOutputChanges) {
263 checkForDeviceAndOutputChanges(checkCloseOutputs);
264 } else {
265 checkCloseOutputs();
266 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100267 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700268 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100269 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700270 const DeviceVector activeMediaDevices =
271 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700273 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530274 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
275 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100276 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700277 // do not force device change on duplicated output because if device is 0, it will
278 // also force a device 0 for the two outputs it is duplicated to which may override
279 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100280 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100281 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700282 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700283 // always force when disconnecting (a non-duplicated device)
284 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100285 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700286 }
jiabinbce0c1d2020-10-05 11:20:18 -0700287 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000288 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700289 desc->supportsDevicesForPlayback(activeMediaDevices)) {
290 // Reopen the output to query the dynamic profiles when there is not active
291 // clients or all active clients will be rerouted. Otherwise, set the flag
292 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
293 // can be reopened to query dynamic profiles when all clients are inactive.
294 if (areAllActiveTracksRerouted(desc)) {
295 outputsToReopen.push_back(mOutputs.keyAt(i));
296 } else {
297 desc->mPendingReopenToQueryProfiles = true;
298 }
299 }
300 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
301 // Clear the flag that previously set for re-querying profiles.
302 desc->mPendingReopenToQueryProfiles = false;
303 }
304 }
305 for (const auto& output : outputsToReopen) {
306 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
307 closeOutput(output);
308 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700309 }
310
Eric Laurentd60560a2015-04-10 11:31:20 -0700311 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100312 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700313 }
314
Eric Laurent72aa32f2014-05-30 18:51:48 -0700315 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700316 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700317 } // end if is output device
318
Eric Laurente552edb2014-03-10 17:42:56 -0700319 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700320 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100321 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700322 switch (state)
323 {
324 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700325 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700326 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100327 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700328 return INVALID_OPERATION;
329 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700330
331 if (mAvailableInputDevices.add(device) < 0) {
332 return NO_MEMORY;
333 }
334
François Gaffie44481e72016-04-20 07:49:57 +0200335 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
336 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100337 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200338
Eric Laurent0dd51852019-04-19 18:18:58 -0700339 if (checkInputsForDevice(device, state) != NO_ERROR) {
340 mAvailableInputDevices.remove(device);
341
François Gaffie11d30102018-11-02 16:09:09 +0100342 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100343
344 mHwModules.cleanUpForDevice(device);
345
Eric Laurentd4692962014-05-05 18:13:44 -0700346 return INVALID_OPERATION;
347 }
348
Eric Laurentd4692962014-05-05 18:13:44 -0700349 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700350
351 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700352 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700353 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100354 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700355 return INVALID_OPERATION;
356 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700357
François Gaffie11d30102018-11-02 16:09:09 +0100358 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700359
360 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100361 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700362
François Gaffie11d30102018-11-02 16:09:09 +0100363 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700364
365 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100366
367 // remove device from mReportedFormatsMap cache
368 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700369 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700370
371 default:
François Gaffie11d30102018-11-02 16:09:09 +0100372 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700373 return BAD_VALUE;
374 }
375
Eric Laurent736a1022019-03-27 18:28:46 -0700376 // Propagate device availability to Engine
377 setEngineDeviceConnectionState(device, state);
378
Eric Laurent0dd51852019-04-19 18:18:58 -0700379 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700380 // As the input device list can impact the output device selection, update
381 // getDeviceForStrategy() cache
382 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700383
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100384 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200385 // Reconnect Audio Source
386 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
387 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
388 checkAudioSourceForAttributes(attributes);
389 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700390 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100391 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700392 }
393
Eric Laurentb52c1522014-05-20 11:27:36 -0700394 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700395 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700396 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700397
François Gaffie11d30102018-11-02 16:09:09 +0100398 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700399 return BAD_VALUE;
400}
401
Eric Laurent736a1022019-03-27 18:28:46 -0700402void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
403 audio_policy_dev_state_t state) {
404
405 // the Engine does not have to know about remote submix devices used by dynamic audio policies
406 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
407 return;
408 }
409 mEngine->setDeviceConnectionState(device, state);
410}
411
412
Eric Laurente0720872014-03-11 09:30:41 -0700413audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100414 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700415{
Eric Laurent634b7142016-04-20 13:48:02 -0700416 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800417 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
418 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700419 (strlen(device_address) != 0)/*matchAddress*/);
420
421 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100422 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700423 device, device_address);
424 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
425 }
François Gaffie53615e22015-03-19 09:24:12 +0100426
Eric Laurent3a4311c2014-03-17 12:00:47 -0700427 DeviceVector *deviceVector;
428
Eric Laurente552edb2014-03-10 17:42:56 -0700429 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700430 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700431 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700432 deviceVector = &mAvailableInputDevices;
433 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100434 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700435 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700436 }
Eric Laurent634b7142016-04-20 13:48:02 -0700437
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800438 return (deviceVector->getDevice(
439 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700440 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800441}
442
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800443status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
444 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800445 const char *device_name,
446 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800447{
448 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700449 String8 reply;
450 AudioParameter param;
451 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800452
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800453 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
454 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800455
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800456 // connect/disconnect only 1 device at a time
457 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
458
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800459 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700460 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800461 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800462 // Nothing to do: device is not connected
463 return NO_ERROR;
464 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800465 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800466
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700467 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800468 // configure codecs.
469 // Handle two specific cases by sending a set parameter to
470 // configure A2DP codecs. No need to toggle device state.
471 // Case 1: A2DP active device switches from primary to primary
472 // module
473 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200474 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700475 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800476 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
477 if (availablePrimaryOutputDevices().contains(devDesc) &&
478 (module != 0 && module->getHandle() == primaryHandle)) {
479 reply = mpClientInterface->getParameters(
480 AUDIO_IO_HANDLE_NONE,
481 String8(AudioParameter::keyReconfigA2dpSupported));
482 AudioParameter repliedParameters(reply);
483 repliedParameters.getInt(
484 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
485 if (isReconfigA2dpSupported) {
486 const String8 key(AudioParameter::keyReconfigA2dp);
487 param.add(key, String8("true"));
488 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
489 devDesc->setEncodedFormat(encodedFormat);
490 return NO_ERROR;
491 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700492 }
493 }
cnx421bd2dcc42020-07-11 14:58:44 +0800494 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
495 for (size_t i = 0; i < mOutputs.size(); i++) {
496 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
497 // mute media strategies and delay device switch by the largest
498 // This avoid sending the music tail into the earpiece or headset.
499 setStrategyMute(musicStrategy, true, desc);
500 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
501 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
502 nullptr, true /*fromCache*/).types());
503 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800504 // Toggle the device state: UNAVAILABLE -> AVAILABLE
505 // This will force reading again the device configuration
506 status = setDeviceConnectionState(device,
507 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800508 device_address, device_name,
509 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800510 if (status != NO_ERROR) {
511 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
512 status);
513 return status;
514 }
515
516 status = setDeviceConnectionState(device,
517 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800518 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800519 if (status != NO_ERROR) {
520 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
521 status);
522 return status;
523 }
524
525 return NO_ERROR;
526}
527
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800528status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
529 std::vector<audio_format_t> *formats)
530{
531 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800532 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800533 std::unordered_set<audio_format_t> formatSet;
534 sp<HwModule> primaryModule =
535 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700536 if (primaryModule == nullptr) {
537 ALOGE("%s() unable to get primary module", __func__);
538 return NO_INIT;
539 }
jiabin9a3361e2019-10-01 09:38:30 -0700540 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
541 getAudioDeviceOutAllA2dpSet());
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800542 for (const auto& device : declaredDevices) {
543 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800544 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800545 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800546 return status;
547}
548
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100549DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
550{
551 DeviceVector rxSinkdevices{};
552 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
553 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
554 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
555 auto rxSinkDevice = rxSinkdevices.itemAt(0);
556 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
557 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
558 // retrieve Rx Source device descriptor
559 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
560 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
561
562 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
563 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
564 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
565 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
566 return DeviceVector(rxSinkDevice);
567 }
568 }
569 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
570 // the device returned is not necessarily reachable via this output
571 // (filter later by setOutputDevices())
572 return getNewOutputDevices(mPrimaryOutput, fromCache);
573}
574
575status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
576{
577 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
578 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
579 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
580 }
581 return INVALID_OPERATION;
582}
583
584status_t AudioPolicyManager::updateCallRoutingInternal(
585 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700586{
587 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100588 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700589 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700590 if(!hasPrimaryOutput() ||
591 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100592 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700593 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100594 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100595
Francois Gaffie716e1432019-01-14 16:58:59 +0100596 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100597 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100598 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100599
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100600 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100601 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700602
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200603 disconnectTelephonyRxAudioSource();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700604 // release TX patch if any
605 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100606 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700607 mCallTxPatch.clear();
608 }
609
François Gaffie9eb18552018-11-05 10:33:26 +0100610 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700611 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100612 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700613 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100614 // retrieve Rx Source and Tx Sink device descriptors
615 sp<DeviceDescriptor> rxSourceDevice =
616 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
617 String8(),
618 AUDIO_FORMAT_DEFAULT);
619 sp<DeviceDescriptor> txSinkDevice =
620 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
621 String8(),
622 AUDIO_FORMAT_DEFAULT);
623
624 // RX and TX Telephony device are declared by Primary Audio HAL
625 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
626 (telephonyRxModule->getHalVersionMajor() >= 3)) {
627 if (rxSourceDevice == 0 || txSinkDevice == 0) {
628 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100629 ALOGE("%s() no telephony Tx and/or RX device", __func__);
630 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100631 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100632 // createAudioPatchInternal now supports both HW / SW bridging
633 createRxPatch = true;
634 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100635 } else {
636 // If the RX device is on the primary HW module, then use legacy routing method for
637 // voice calls via setOutputDevice() on primary output.
638 // Otherwise, create two audio patches for TX and RX path.
639 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
640 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700641 // If the TX device is also on the primary HW module, setOutputDevice() will take care
642 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100643 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
644 (txSinkDevice != 0);
645 }
646 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
647 // Otherwise, create two audio patches for TX and RX path.
648 if (!createRxPatch) {
649 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700650 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200651 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800652 // If the TX device is on the primary HW module but RX device is
653 // on other HW module, SinkMetaData of telephony input should handle it
654 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700655 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700656 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100657 // terminate active capture if on the same HW module as the call TX source device
658 // FIXME: would be better to refine to only inputs whose profile connects to the
659 // call TX device but this information is not in the audio patch and logic here must be
660 // symmetric to the one in startInput()
661 for (const auto& activeDesc : mInputs.getActiveInputs()) {
662 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
663 closeActiveClients(activeDesc);
664 }
665 }
François Gaffie9eb18552018-11-05 10:33:26 +0100666 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800667 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100668 if (waitMs != nullptr) {
669 *waitMs = muteWaitMs;
670 }
671 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800672}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700673
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800674sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100675 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700676 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700677
François Gaffie11d30102018-11-02 16:09:09 +0100678 if (device == nullptr) {
679 return nullptr;
680 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100681
682 // @TODO: still ignoring the address, or not dealing platform with multiple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800683 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100684 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800685 addSource(mAvailableInputDevices.getDevice(
686 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800687 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100688 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800689 addSink(mAvailableOutputDevices.getDevice(
690 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800691 }
692
François Gaffieafd4cea2019-11-18 15:50:22 +0100693 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
694 status_t status =
695 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
696 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
697 if (status != NO_ERROR || index < 0) {
698 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
699 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800700 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100701 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800702}
703
Mikhail Naganov100f0122018-11-29 11:22:16 -0800704bool AudioPolicyManager::isDeviceOfModule(
705 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
706 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
707 if (module != 0) {
708 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
709 .indexOf(devDesc) != NAME_NOT_FOUND
710 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
711 .indexOf(devDesc) != NAME_NOT_FOUND;
712 }
713 return false;
714}
715
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200716void AudioPolicyManager::connectTelephonyRxAudioSource()
717{
718 disconnectTelephonyRxAudioSource();
719 const struct audio_port_config source = {
720 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
721 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
722 };
723 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
724 status_t status = startAudioSource(&source, &aa, &mCallRxSourceClientPort, 0/*uid*/);
725 ALOGE_IF(status != NO_ERROR, "%s failed to start Telephony Rx AudioSource", __func__);
726}
727
728void AudioPolicyManager::disconnectTelephonyRxAudioSource()
729{
730 stopAudioSource(mCallRxSourceClientPort);
731 mCallRxSourceClientPort = AUDIO_PORT_HANDLE_NONE;
732}
733
Eric Laurente0720872014-03-11 09:30:41 -0700734void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700735{
736 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100737 // store previous phone state for management of sonification strategy below
738 int oldState = mEngine->getPhoneState();
739
740 if (mEngine->setPhoneState(state) != NO_ERROR) {
741 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700742 return;
743 }
François Gaffie2110e042015-03-24 08:41:51 +0100744 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700745 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700746 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700747 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800748 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700749 }
750
François Gaffie2110e042015-03-24 08:41:51 +0100751 /**
752 * Switching to or from incall state or switching between telephony and VoIP lead to force
753 * routing command.
754 */
Eric Laurent74b71512019-11-06 17:21:57 -0800755 bool force = ((isStateInCall(oldState) != isStateInCall(state))
756 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700757
758 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700759 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700760
Eric Laurente552edb2014-03-10 17:42:56 -0700761 int delayMs = 0;
762 if (isStateInCall(state)) {
763 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100764 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
765 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700766 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700767 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700768 // mute media and sonification strategies and delay device switch by the largest
769 // latency of any output where either strategy is active.
770 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100771 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
772 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
773 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700774 (delayMs < (int)desc->latency()*2)) {
775 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700776 }
François Gaffiec005e562018-11-06 15:04:49 +0100777 setStrategyMute(musicStrategy, true, desc);
778 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
779 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
780 nullptr, true /*fromCache*/).types());
781 setStrategyMute(sonificationStrategy, true, desc);
782 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
783 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
784 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700785 }
786 }
787
Eric Laurent87ffa392015-05-22 10:32:38 -0700788 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700789 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100790 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700791 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100792 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
793 // force routing command to audio hardware when ending call
794 // even if no device change is needed
795 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
796 rxDevices = mPrimaryOutput->devices();
797 }
798 if (oldState == AUDIO_MODE_IN_CALL) {
799 disconnectTelephonyRxAudioSource();
800 if (mCallTxPatch != 0) {
801 releaseAudioPatchInternal(mCallTxPatch->getHandle());
802 mCallTxPatch.clear();
803 }
804 }
François Gaffie11d30102018-11-02 16:09:09 +0100805 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700806 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700807 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700808
809 // reevaluate routing on all outputs in case tracks have been started during the call
810 for (size_t i = 0; i < mOutputs.size(); i++) {
811 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100812 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700813 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100814 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700815 }
816 }
817
Eric Laurente552edb2014-03-10 17:42:56 -0700818 if (isStateInCall(state)) {
819 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700820 // force reevaluating accessibility routing when call starts
821 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700822 }
823
824 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100825 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
826 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700827}
828
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700829audio_mode_t AudioPolicyManager::getPhoneState() {
830 return mEngine->getPhoneState();
831}
832
Eric Laurente0720872014-03-11 09:30:41 -0700833void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100834 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700835{
François Gaffie2110e042015-03-24 08:41:51 +0100836 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700837 if (config == mEngine->getForceUse(usage)) {
838 return;
839 }
Eric Laurente552edb2014-03-10 17:42:56 -0700840
François Gaffie2110e042015-03-24 08:41:51 +0100841 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
842 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
843 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700844 }
François Gaffie2110e042015-03-24 08:41:51 +0100845 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
846 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
847 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700848
849 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700850 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800851
Eric Laurent22fcda22019-05-17 16:28:47 -0700852 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
853 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
854 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
855 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
856 }
857
Eric Laurentdc462862016-07-19 12:29:53 -0700858 //FIXME: workaround for truncated touch sounds
859 // to be removed when the problem is handled by system UI
860 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700861 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
862 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
863 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700864
865 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100866 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700867}
868
Eric Laurente0720872014-03-11 09:30:41 -0700869void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700870{
871 ALOGV("setSystemProperty() property %s, value %s", property, value);
872}
873
Michael Chana94fbb22018-04-24 14:31:19 +1000874// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
875// search to profiles for direct outputs.
876sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100877 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000878 uint32_t samplingRate,
879 audio_format_t format,
880 audio_channel_mask_t channelMask,
881 audio_output_flags_t flags,
882 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700883{
Michael Chana94fbb22018-04-24 14:31:19 +1000884 if (directOnly) {
885 // only retain flags that will drive the direct output profile selection
886 // if explicitly requested
887 static const uint32_t kRelevantFlags =
888 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lataba810b82019-07-03 11:15:33 -0700889 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000890 flags =
891 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
892 }
Eric Laurent861a6282015-05-18 15:40:16 -0700893
894 sp<IOProfile> profile;
895
Mikhail Naganovd4120142017-12-06 15:49:22 -0800896 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800897 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100898 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700899 samplingRate, NULL /*updatedSamplingRate*/,
900 format, NULL /*updatedFormat*/,
901 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700902 flags)) {
903 continue;
904 }
905 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100906 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700907 continue;
908 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800909 // reject profiles if connected device does not support codec
jiabin9a3361e2019-10-01 09:38:30 -0700910 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800911 continue;
912 }
Michael Chana94fbb22018-04-24 14:31:19 +1000913 if (!directOnly) return curProfile;
914 // when searching for direct outputs, if several profiles are compatible, give priority
915 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100916 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700917 continue;
918 }
919 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100920 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700921 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700922 }
Eric Laurente552edb2014-03-10 17:42:56 -0700923 }
924 }
Eric Laurent861a6282015-05-18 15:40:16 -0700925 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700926}
927
Eric Laurentfa0f6742021-08-17 18:39:44 +0200928sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +0200929 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200930{
931 for (const auto& hwModule : mHwModules) {
932 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200933 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200934 continue;
935 }
936 // reject profiles not corresponding to a device currently available
937 DeviceVector supportedDevices = curProfile->getSupportedDevices();
938 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
939 continue;
940 }
941 if (!devices.empty()) {
942 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
943 != devices.size()) {
944 continue;
945 }
946 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200947 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
948 return curProfile;
949 }
950 }
951 return nullptr;
952}
953
Eric Laurentf4e63452017-11-06 19:31:46 +0000954audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700955{
François Gaffiec005e562018-11-06 15:04:49 +0100956 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800957
958 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
959 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
960 // format, flags, etc. This may result in some discrepancy for functions that utilize
961 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
962 // and AudioSystem::getOutputSamplingRate().
963
François Gaffie11d30102018-11-02 16:09:09 +0100964 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700965 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700966
François Gaffie11d30102018-11-02 16:09:09 +0100967 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
968 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000969 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700970}
971
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700972status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
973 const audio_attributes_t *srcAttr,
974 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700975{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700976 if (srcAttr != NULL) {
977 if (!isValidAttributes(srcAttr)) {
978 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
979 __func__,
980 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
981 srcAttr->tags);
982 return BAD_VALUE;
983 }
984 *dstAttr = *srcAttr;
985 } else {
986 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
987 ALOGE("%s: invalid stream type", __func__);
988 return BAD_VALUE;
989 }
François Gaffiec005e562018-11-06 15:04:49 +0100990 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700991 }
Eric Laurent22fcda22019-05-17 16:28:47 -0700992
993 // Only honor audibility enforced when required. The client will be
994 // forced to reconnect if the forced usage changes.
995 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700996 dstAttr->flags = static_cast<audio_flags_mask_t>(
997 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -0700998 }
999
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001000 return NO_ERROR;
1001}
1002
Kevin Rocard153f92d2018-12-18 18:33:28 -08001003status_t AudioPolicyManager::getOutputForAttrInt(
1004 audio_attributes_t *resultAttr,
1005 audio_io_handle_t *output,
1006 audio_session_t session,
1007 const audio_attributes_t *attr,
1008 audio_stream_type_t *stream,
1009 uid_t uid,
1010 const audio_config_t *config,
1011 audio_output_flags_t *flags,
1012 audio_port_handle_t *selectedDeviceId,
1013 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001014 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001015 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001016{
François Gaffiec005e562018-11-06 15:04:49 +01001017 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001018 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001019 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001020 const sp<DeviceDescriptor> requestedDevice =
1021 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1022
Eric Laurent8a1095a2019-11-08 14:44:16 -08001023 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001024 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1025 if (status != NO_ERROR) {
1026 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001027 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001028 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001029 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001030 }
François Gaffiec005e562018-11-06 15:04:49 +01001031 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001032
François Gaffiec005e562018-11-06 15:04:49 +01001033 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1034 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001035
Kevin Rocard153f92d2018-12-18 18:33:28 -08001036 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1037 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1038 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001039 sp<AudioPolicyMix> primaryMix;
1040 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001041 if (status != OK) {
1042 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001043 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001044
Kevin Rocard153f92d2018-12-18 18:33:28 -08001045 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001046 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001047
1048 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -07001049 if ((usePrimaryOutputFromPolicyMixes
1050 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -08001051 && !audio_is_linear_pcm(config->format)) {
1052 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001053 return BAD_VALUE;
1054 }
1055 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001056 sp<DeviceDescriptor> deviceDesc =
1057 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1058 primaryMix->mDeviceAddress,
1059 AUDIO_FORMAT_DEFAULT);
1060 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001061 if (deviceDesc != nullptr
1062 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001063 audio_io_handle_t newOutput;
1064 status = openDirectOutput(
1065 *stream, session, config,
1066 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1067 DeviceVector(deviceDesc), &newOutput);
1068 if (status != NO_ERROR) {
1069 policyDesc = nullptr;
1070 } else {
1071 policyDesc = mOutputs.valueFor(newOutput);
1072 primaryMix->setOutput(policyDesc);
1073 }
1074 }
1075 if (policyDesc != nullptr) {
1076 policyDesc->mPolicyMix = primaryMix;
1077 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001078 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001079
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001080 ALOGV("getOutputForAttr() returns output %d", *output);
1081 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1082 *outputType = API_OUT_MIX_PLAYBACK;
1083 } else {
1084 *outputType = API_OUTPUT_LEGACY;
1085 }
1086 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001087 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001088 }
François Gaffiec005e562018-11-06 15:04:49 +01001089 // Virtual sources must always be dynamicaly or explicitly routed
1090 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1091 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1092 return BAD_VALUE;
1093 }
1094 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1095 // in order to let the choice of the order to future vendor engine
1096 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001097
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001098 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001099 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001100 }
1101
Nadav Barb2f18162018-07-18 13:01:53 +03001102 // Set incall music only if device was explicitly set, and fallback to the device which is
1103 // chosen by the engine if not.
1104 // FIXME: provide a more generic approach which is not device specific and move this back
1105 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001106 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001107 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001108 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001109 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001110 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001111 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001112 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001113 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001114 }
1115 }
1116
François Gaffiec005e562018-11-06 15:04:49 +01001117 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1118 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1119 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001120
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001121 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001122 if (!msdDevices.isEmpty()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001123 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001124 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001125 ALOGV("%s() Using MSD devices %s instead of devices %s",
1126 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001127 } else {
1128 *output = AUDIO_IO_HANDLE_NONE;
1129 }
1130 }
1131 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001132 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurent42984412019-05-09 17:57:03 -07001133 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001134 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001135 if (*output == AUDIO_IO_HANDLE_NONE) {
1136 return INVALID_OPERATION;
1137 }
Paul McLeanaa981192015-03-21 09:55:15 -07001138
François Gaffiec005e562018-11-06 15:04:49 +01001139 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001140 for (auto &outputDevice : outputDevices) {
1141 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1142 *selectedDeviceId = outputDevice->getId();
1143 break;
1144 }
1145 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001146
Eric Laurent8a1095a2019-11-08 14:44:16 -08001147 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1148 *outputType = API_OUTPUT_TELEPHONY_TX;
1149 } else {
1150 *outputType = API_OUTPUT_LEGACY;
1151 }
1152
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001153 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1154
1155 return NO_ERROR;
1156}
1157
1158status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1159 audio_io_handle_t *output,
1160 audio_session_t session,
1161 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001162 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001163 const audio_config_t *config,
1164 audio_output_flags_t *flags,
1165 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001166 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001167 std::vector<audio_io_handle_t> *secondaryOutputs,
1168 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001169{
1170 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1171 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1172 return INVALID_OPERATION;
1173 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001174 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001175 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001176 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001177 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001178 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001179 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001180 const sp<DeviceDescriptor> requestedDevice =
1181 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1182
1183 // Prevent from storing invalid requested device id in clients
1184 const audio_port_handle_t sanitizedRequestedPortId =
1185 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1186 *selectedDeviceId = sanitizedRequestedPortId;
1187
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001188 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001189 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001190 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001191 if (status != NO_ERROR) {
1192 return status;
1193 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001194 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001195 if (secondaryOutputs != nullptr) {
1196 for (auto &secondaryMix : secondaryMixes) {
1197 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1198 if (outputDesc != nullptr &&
1199 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1200 secondaryOutputs->push_back(outputDesc->mIoHandle);
1201 weakSecondaryOutputDescs.push_back(outputDesc);
1202 }
1203 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001204 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001205
Eric Laurent8fc147b2018-07-22 19:13:55 -07001206 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001207 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001208 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001209 };
jiabin4ef93452019-09-10 14:29:54 -07001210 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001211
Eric Laurentc209fe42020-06-05 18:11:23 -07001212 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001213 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001214 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001215 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001216 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001217 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001218 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001219 std::move(weakSecondaryOutputDescs),
1220 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001221 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001222
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001223 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1224 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001225
Eric Laurente83b55d2014-11-14 10:06:21 -08001226 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001227}
1228
Eric Laurentc529cf62020-04-17 18:19:10 -07001229status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1230 audio_session_t session,
1231 const audio_config_t *config,
1232 audio_output_flags_t flags,
1233 const DeviceVector &devices,
1234 audio_io_handle_t *output) {
1235
1236 *output = AUDIO_IO_HANDLE_NONE;
1237
1238 // skip direct output selection if the request can obviously be attached to a mixed output
1239 // and not explicitly requested
1240 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1241 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1242 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1243 return NAME_NOT_FOUND;
1244 }
1245
1246 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1247 // This prevents creating an offloaded track and tearing it down immediately after start
1248 // when audioflinger detects there is an active non offloadable effect.
1249 // FIXME: We should check the audio session here but we do not have it in this context.
1250 // This may prevent offloading in rare situations where effects are left active by apps
1251 // in the background.
1252 sp<IOProfile> profile;
1253 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1254 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1255 profile = getProfileForOutput(
1256 devices, config->sample_rate, config->format, config->channel_mask,
1257 flags, true /* directOnly */);
1258 }
1259
1260 if (profile == nullptr) {
1261 return NAME_NOT_FOUND;
1262 }
1263
1264 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1265 for (size_t i = 0; i < mOutputs.size(); i++) {
1266 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1267 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1268 // reuse direct output if currently open by the same client
1269 // and configured with same parameters
1270 if ((config->sample_rate == desc->getSamplingRate()) &&
1271 (config->format == desc->getFormat()) &&
1272 (config->channel_mask == desc->getChannelMask()) &&
1273 (session == desc->mDirectClientSession)) {
1274 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001275 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001276 mOutputs.keyAt(i), session);
1277 *output = mOutputs.keyAt(i);
1278 return NO_ERROR;
1279 }
1280 }
1281 }
1282
1283 if (!profile->canOpenNewIo()) {
1284 return NAME_NOT_FOUND;
1285 }
1286
1287 sp<SwAudioOutputDescriptor> outputDesc =
1288 new SwAudioOutputDescriptor(profile, mpClientInterface);
1289
Michael Chan6fb34492020-12-08 15:44:49 +11001290 // An MSD patch may be using the only output stream that can service this request. Release
1291 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001292 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001293
Eric Laurentf1f22e72021-07-13 14:04:14 +02001294 status_t status =
1295 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001296
1297 // only accept an output with the requested parameters
1298 if (status != NO_ERROR ||
1299 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1300 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1301 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1302 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1303 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1304 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1305 config->channel_mask, outputDesc->getChannelMask());
1306 if (*output != AUDIO_IO_HANDLE_NONE) {
1307 outputDesc->close();
1308 }
1309 // fall back to mixer output if possible when the direct output could not be open
1310 if (audio_is_linear_pcm(config->format) &&
1311 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1312 return NAME_NOT_FOUND;
1313 }
1314 *output = AUDIO_IO_HANDLE_NONE;
1315 return BAD_VALUE;
1316 }
1317 outputDesc->mDirectOpenCount = 1;
1318 outputDesc->mDirectClientSession = session;
1319
1320 addOutput(*output, outputDesc);
1321 mPreviousOutputs = mOutputs;
1322 ALOGV("%s returns new direct output %d", __func__, *output);
1323 mpClientInterface->onAudioPortListUpdate();
1324 return NO_ERROR;
1325}
1326
François Gaffie11d30102018-11-02 16:09:09 +01001327audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1328 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001329 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001330 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001331 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001332 audio_output_flags_t *flags,
1333 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001334{
Andy Hungc88b0642018-04-27 15:42:35 -07001335 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001336
jiabine375d412019-02-26 12:54:53 -08001337 // Discard haptic channel mask when forcing muting haptic channels.
1338 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001339 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1340 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001341
Eric Laurente552edb2014-03-10 17:42:56 -07001342 // open a direct output if required by specified parameters
1343 //force direct flag if offload flag is set: offloading implies a direct output stream
1344 // and all common behaviors are driven by checking only the direct flag
1345 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001346 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1347 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001348 }
Nadav Bar766fb022018-01-07 12:18:03 +02001349 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1350 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001351 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001352
1353 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1354
Eric Laurente83b55d2014-11-14 10:06:21 -08001355 // only allow deep buffering for music stream type
1356 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001357 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001358 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001359 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001360 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1361 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001362 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001363 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001364 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001365 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001366 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001367 audio_is_linear_pcm(config->format) &&
1368 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001369 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001370 AUDIO_OUTPUT_FLAG_DIRECT);
1371 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001372 }
Eric Laurente552edb2014-03-10 17:42:56 -07001373
Eric Laurentfa0f6742021-08-17 18:39:44 +02001374 if (mSpatializerOutput != nullptr
1375 && canBeSpatialized(attr, config, devices.toTypeAddrVector())) {
1376 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001377 }
1378
Eric Laurentc529cf62020-04-17 18:19:10 -07001379 audio_config_t directConfig = *config;
1380 directConfig.channel_mask = channelMask;
1381 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1382 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001383 return output;
1384 }
1385
Eric Laurent14cbfca2016-03-17 09:42:16 -07001386 // A request for HW A/V sync cannot fallback to a mixed output because time
1387 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001388 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001389 return AUDIO_IO_HANDLE_NONE;
1390 }
1391
Eric Laurente552edb2014-03-10 17:42:56 -07001392 // ignoring channel mask due to downmix capability in mixer
1393
1394 // open a non direct output
1395
1396 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001397 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001398 // get which output is suitable for the specified stream. The actual
1399 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001400 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001401
Eric Laurent8838a382014-09-08 16:44:28 -07001402 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001403 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001404 output = selectOutput(
1405 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001406 }
François Gaffie11d30102018-11-02 16:09:09 +01001407 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001408 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001409 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001410
Eric Laurente552edb2014-03-10 17:42:56 -07001411 return output;
1412}
1413
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001414sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001415 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1416 mAvailableInputDevices);
1417 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1418}
1419
1420DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1421 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1422 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001423}
1424
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001425const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001426 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001427 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1428 if (msdModule != 0) {
1429 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1430 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1431 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1432 const struct audio_port_config *source = &patch->mPatch.sources[j];
1433 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1434 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001435 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001436 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001437 }
1438 }
1439 }
1440 return msdPatches;
1441}
1442
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001443status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1444 const InputProfileCollection &inputProfiles,
1445 const OutputProfileCollection &outputProfiles,
1446 const sp<DeviceDescriptor> &sourceDevice,
1447 const sp<DeviceDescriptor> &sinkDevice,
1448 AudioProfileVector& sourceProfiles,
1449 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001450 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001451 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001452 return NO_INIT;
1453 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001454 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001455 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001456 return NO_INIT;
1457 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001458 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001459 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1460 inProfile->supportsDevice(sourceDevice)) {
1461 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001462 }
1463 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001464 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001465 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001466 outProfile->supportsDevice(sinkDevice)) {
1467 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001468 }
1469 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001470 return NO_ERROR;
1471}
1472
1473status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1474 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1475 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1476{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001477 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001478 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1479 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1480 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001481 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001482 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1483 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001484 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001485 }
1486 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1487 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1488 sinkConfig->format = bestSinkConfig.format;
1489 // For encoded streams force direct flag to prevent downstream mixing.
1490 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1491 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001492 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1493 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001494 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001495 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1496 // raw and IEC61937 framed streams.
1497 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1498 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1499 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001500 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1501 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1502 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1503 sourceConfig->format = bestSinkConfig.format;
1504 // Copy input stream directly without any processing (e.g. resampling).
1505 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1506 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1507 if (hwAvSync) {
1508 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1509 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1510 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1511 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1512 }
1513 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1514 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1515 sinkConfig->config_mask |= config_mask;
1516 sourceConfig->config_mask |= config_mask;
1517 return NO_ERROR;
1518}
1519
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001520PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1521 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001522{
1523 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001524 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1525 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1526 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1527 if (deviceModule == nullptr) {
1528 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1529 return patchBuilder;
1530 }
1531 const InputProfileCollection inputProfiles = msdIsSource ?
1532 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1533 const OutputProfileCollection outputProfiles = msdIsSource ?
1534 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1535
1536 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1537 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1538 device : getMsdAudioOutDevices().itemAt(0);
1539 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1540
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001541 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1542 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001543 AudioProfileVector sourceProfiles;
1544 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001545 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1546 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001547 for (auto hwAvSync : { true, false }) {
1548 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1549 sourceProfiles, sinkProfiles) != NO_ERROR) {
1550 continue;
1551 }
1552 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1553 &sinkConfig) == NO_ERROR) {
1554 // Found a matching config. Re-create PatchBuilder with this config.
1555 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1556 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001557 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001558 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001559 " supporting PCM format conversion.", __func__);
1560 return patchBuilder;
1561}
1562
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001563status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001564 DeviceVector devices;
1565 if (outputDevices != nullptr && outputDevices->size() > 0) {
1566 devices.add(*outputDevices);
1567 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001568 // Use media strategy for unspecified output device. This should only
1569 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1570 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001571 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001572 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001573 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001574 }
Michael Chan6fb34492020-12-08 15:44:49 +11001575 std::vector<PatchBuilder> patchesToCreate;
1576 for (auto i = 0u; i < devices.size(); ++i) {
1577 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001578 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001579 }
1580 // Retain only the MSD patches associated with outputDevices request.
1581 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001582 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001583 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1584 auto retainedPatch = false;
1585 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1586 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1587 patchesToRemove.removeItemsAt(i);
1588 retainedPatch = true;
1589 break;
1590 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001591 }
Michael Chan6fb34492020-12-08 15:44:49 +11001592 if (retainedPatch) {
1593 it = patchesToCreate.erase(it);
1594 continue;
1595 }
1596 ++it;
1597 }
1598 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1599 return NO_ERROR;
1600 }
1601 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1602 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001603 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001604 }
Michael Chan6fb34492020-12-08 15:44:49 +11001605 status_t status = NO_ERROR;
1606 for (const auto &p : patchesToCreate) {
1607 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1608 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1609 char message[256];
1610 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1611 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1612 currStatus == NO_ERROR ? "Success" : "Error",
1613 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1614 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1615 if (currStatus == NO_ERROR) {
1616 ALOGD("%s", message);
1617 } else {
1618 ALOGE("%s", message);
1619 if (status == NO_ERROR) {
1620 status = currStatus;
1621 }
1622 }
1623 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001624 return status;
1625}
1626
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001627void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1628 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001629 for (size_t i = 0; i < msdPatches.size(); i++) {
1630 const auto& patch = msdPatches[i];
1631 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1632 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1633 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1634 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1635 releaseAudioPatch(patch->getHandle(), mUidCached);
1636 break;
1637 }
1638 }
1639 }
1640}
1641
Eric Laurente0720872014-03-11 09:30:41 -07001642audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001643 audio_output_flags_t flags,
1644 audio_format_t format,
1645 audio_channel_mask_t channelMask,
1646 uint32_t samplingRate,
1647 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001648{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001649 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1650 "%s called with format %#x", __func__, format);
1651
jiabinebb6af42020-06-09 17:31:17 -07001652 // Return the output that haptic-generating attached to when 1) session id is specified,
1653 // 2) haptic-generating effect exists for given session id and 3) the output that
1654 // haptic-generating effect attached to is in given outputs.
1655 if (sessionId != AUDIO_SESSION_NONE) {
1656 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1657 sessionId, FX_IID_HAPTICGENERATOR);
1658 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1659 return hapticGeneratingOutput;
1660 }
1661 }
1662
Eric Laurent16c66dd2019-05-01 17:54:10 -07001663 // Flags disqualifying an output: the match must happen before calling selectOutput()
1664 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1665 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1666
1667 // Flags expressing a functional request: must be honored in priority over
1668 // other criteria
1669 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1670 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1671 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1672 // Flags expressing a performance request: have lower priority than serving
1673 // requested sampling rate or channel mask
1674 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1675 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1676 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1677
1678 const audio_output_flags_t functionalFlags =
1679 (audio_output_flags_t)(flags & kFunctionalFlags);
1680 const audio_output_flags_t performanceFlags =
1681 (audio_output_flags_t)(flags & kPerformanceFlags);
1682
1683 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1684
Eric Laurente552edb2014-03-10 17:42:56 -07001685 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001686 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001687 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001688 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001689 // 2: the output with the highest number of requested functional flags
1690 // 3: the output supporting the exact channel mask
1691 // 4: the output with a higher channel count than requested
1692 // 5: the output with a higher sampling rate than requested
1693 // 6: the output with the highest number of requested performance flags
1694 // 7: the output with the bit depth the closest to the requested one
1695 // 8: the primary output
1696 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001697
Eric Laurent16c66dd2019-05-01 17:54:10 -07001698 // matching criteria values in priority order for best matching output so far
1699 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001700
Eric Laurent16c66dd2019-05-01 17:54:10 -07001701 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1702 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1703 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001704
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001705 for (audio_io_handle_t output : outputs) {
1706 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001707 // matching criteria values in priority order for current output
1708 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001709
Eric Laurent16c66dd2019-05-01 17:54:10 -07001710 if (outputDesc->isDuplicated()) {
1711 continue;
1712 }
1713 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1714 continue;
1715 }
Eric Laurent8838a382014-09-08 16:44:28 -07001716
Eric Laurent16c66dd2019-05-01 17:54:10 -07001717 // If haptic channel is specified, use the haptic output if present.
1718 // When using haptic output, same audio format and sample rate are required.
1719 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001720 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001721 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1722 continue;
1723 }
1724 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001725 && format == outputDesc->getFormat()
1726 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001727 currentMatchCriteria[0] = outputHapticChannelCount;
1728 }
1729
1730 // functional flags match
1731 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1732
1733 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001734 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1735 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001736 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1737 channelCount <= outputChannelCount) {
1738 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001739 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1740 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001741 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001742 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001743 currentMatchCriteria[3] = outputChannelCount;
1744 }
1745
1746 // sampling rate match
1747 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001748 samplingRate <= outputDesc->getSamplingRate()) {
1749 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001750 }
1751
1752 // performance flags match
1753 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1754
1755 // format match
1756 if (format != AUDIO_FORMAT_INVALID) {
1757 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001758 PolicyAudioPort::kFormatDistanceMax -
1759 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001760 }
1761
1762 // primary output match
1763 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1764
1765 // compare match criteria by priority then value
1766 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1767 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1768 bestMatchCriteria = currentMatchCriteria;
1769 bestOutput = output;
1770
1771 std::stringstream result;
1772 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1773 std::ostream_iterator<int>(result, " "));
1774 ALOGV("%s new bestOutput %d criteria %s",
1775 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001776 }
1777 }
1778
Eric Laurent16c66dd2019-05-01 17:54:10 -07001779 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001780}
1781
Eric Laurent8fc147b2018-07-22 19:13:55 -07001782status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001783{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001784 ALOGV("%s portId %d", __FUNCTION__, portId);
1785
1786 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1787 if (outputDesc == 0) {
1788 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001789 return BAD_VALUE;
1790 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001791 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001792
Eric Laurent8fc147b2018-07-22 19:13:55 -07001793 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001794 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001795
Eric Laurent733ce942017-12-07 12:18:25 -08001796 status_t status = outputDesc->start();
1797 if (status != NO_ERROR) {
1798 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001799 }
1800
Eric Laurent97ac8712018-07-27 18:59:02 -07001801 uint32_t delayMs;
1802 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001803
1804 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001805 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001806 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001807 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001808 if (delayMs != 0) {
1809 usleep(delayMs * 1000);
1810 }
1811
1812 return status;
1813}
1814
Eric Laurent97ac8712018-07-27 18:59:02 -07001815status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1816 const sp<TrackClientDescriptor>& client,
1817 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001818{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001819 // cannot start playback of STREAM_TTS if any other output is being used
1820 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001821
1822 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001823 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001824 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001825 auto clientStrategy = client->strategy();
1826 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001827 if (stream == AUDIO_STREAM_TTS) {
1828 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001829 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001830 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001831 return INVALID_OPERATION;
1832 } else {
1833 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1834 }
1835 } else {
1836 // some playback other than beacon starts
1837 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1838 }
1839
Eric Laurent77305a62016-07-25 16:39:22 -07001840 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001841 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001842 bool force = !outputDesc->isActive() &&
1843 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001844
François Gaffie11d30102018-11-02 16:09:09 +01001845 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001846 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001847 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001848 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001849 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001850 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001851 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001852 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001853 } else {
1854 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001855 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001856 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1857 AUDIO_FORMAT_DEFAULT);
1858 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1859 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001860 }
1861
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001862 // requiresMuteCheck is false when we can bypass mute strategy.
1863 // It covers a common case when there is no materially active audio
1864 // and muting would result in unnecessary delay and dropped audio.
1865 const uint32_t outputLatencyMs = outputDesc->latency();
1866 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1867
Eric Laurente552edb2014-03-10 17:42:56 -07001868 // increment usage count for this stream on the requested output:
1869 // NOTE that the usage count is the same for duplicated output and hardware output which is
1870 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001871 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001872
1873 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001874 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1875 client->isPreferredDeviceForExclusiveUse()) {
1876 // Preferred device may be exclusive, use only if no other active clients on this output
1877 devices = DeviceVector(
1878 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1879 } else {
1880 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1881 }
François Gaffie11d30102018-11-02 16:09:09 +01001882 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001883 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001884 }
1885 }
Eric Laurente552edb2014-03-10 17:42:56 -07001886
François Gaffiec005e562018-11-06 15:04:49 +01001887 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001888 selectOutputForMusicEffects();
1889 }
1890
François Gaffie1c878552018-11-22 16:53:21 +01001891 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001892 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001893 if (devices.isEmpty()) {
1894 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001895 }
François Gaffiec005e562018-11-06 15:04:49 +01001896 bool shouldWait =
1897 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1898 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1899 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001900 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001901 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001902 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001903 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001904 // An output has a shared device if
1905 // - managed by the same hw module
1906 // - supports the currently selected device
1907 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001908 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001909
Eric Laurent77305a62016-07-25 16:39:22 -07001910 // force a device change if any other output is:
1911 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001912 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001913 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001914 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001915 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001916 // change the device currently selected by the other output.
1917 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001918 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001919 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001920 force = true;
1921 }
1922 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001923 // a notification so that audio focus effect can propagate, or that a mute/unmute
1924 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001925 const uint32_t latencyMs = desc->latency();
1926 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1927
1928 if (shouldWait && isActive && (waitMs < latencyMs)) {
1929 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001930 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001931
1932 // Require mute check if another output is on a shared device
1933 // and currently active to have proper drain and avoid pops.
1934 // Note restoring AudioTracks onto this output needs to invoke
1935 // a volume ramp if there is no mute.
1936 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001937 }
1938 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001939
1940 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001941 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001942
Eric Laurente552edb2014-03-10 17:42:56 -07001943 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001944 auto &curves = getVolumeCurves(client->attributes());
1945 checkAndSetVolume(curves, client->volumeSource(),
1946 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001947 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001948 outputDesc->devices().types(), 0 /*delay*/,
1949 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001950
1951 // update the outputs if starting an output with a stream that can affect notification
1952 // routing
1953 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001954
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001955 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001956 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001957 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1958 }
Eric Laurentdc462862016-07-19 12:29:53 -07001959
1960 if (waitMs > muteWaitMs) {
1961 *delayMs = waitMs - muteWaitMs;
1962 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001963
1964 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1965 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1966 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1967 // change occurs after the MixerThread starts and causes a stream volume
1968 // glitch.
1969 //
1970 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001971 }
Eric Laurentdc462862016-07-19 12:29:53 -07001972
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001973 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07001974 mEngine->getForceUse(
1975 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001976 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001977 }
1978
Eric Laurent97ac8712018-07-27 18:59:02 -07001979 // Automatically enable the remote submix input when output is started on a re routing mix
1980 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07001981 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1982 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001983 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1984 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1985 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001986 "remote-submix",
1987 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001988 }
1989
Eric Laurente552edb2014-03-10 17:42:56 -07001990 return NO_ERROR;
1991}
1992
Eric Laurent8fc147b2018-07-22 19:13:55 -07001993status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001994{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001995 ALOGV("%s portId %d", __FUNCTION__, portId);
1996
1997 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1998 if (outputDesc == 0) {
1999 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002000 return BAD_VALUE;
2001 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002002 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002003
Eric Laurent97ac8712018-07-27 18:59:02 -07002004 ALOGV("stopOutput() output %d, stream %d, session %d",
2005 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002006
Eric Laurent97ac8712018-07-27 18:59:02 -07002007 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002008
Eric Laurent733ce942017-12-07 12:18:25 -08002009 if (status == NO_ERROR ) {
2010 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002011 }
2012 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002013}
2014
Eric Laurent97ac8712018-07-27 18:59:02 -07002015status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2016 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002017{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002018 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002019 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002020 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07002021
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002022 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2023
François Gaffie1c878552018-11-22 16:53:21 +01002024 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2025 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002026 // Automatically disable the remote submix input when output is stopped on a
2027 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002028 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002029 if (isSingleDeviceType(
2030 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002031 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002032 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002033 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2034 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002035 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002036 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002037 }
2038 }
2039 bool forceDeviceUpdate = false;
2040 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002041 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002042 forceDeviceUpdate = true;
2043 }
2044
Eric Laurente552edb2014-03-10 17:42:56 -07002045 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002046 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002047
Eric Laurente552edb2014-03-10 17:42:56 -07002048 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002049 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002050 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002051 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002052 // delay the device switch by twice the latency because stopOutput() is executed when
2053 // the track stop() command is received and at that time the audio track buffer can
2054 // still contain data that needs to be drained. The latency only covers the audio HAL
2055 // and kernel buffers. Also the latency does not always include additional delay in the
2056 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01002057 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07002058
2059 // force restoring the device selection on other active outputs if it differs from the
2060 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002061 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002062 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002063 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002064 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002065 desc->isActive() &&
2066 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002067 (newDevices != desc->devices())) {
2068 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2069 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002070
François Gaffie11d30102018-11-02 16:09:09 +01002071 setOutputDevices(desc, newDevices2, force, delayMs);
2072
Eric Laurent57de36c2016-09-28 16:59:11 -07002073 // re-apply device specific volume if not done by setOutputDevice()
2074 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002075 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002076 }
Eric Laurente552edb2014-03-10 17:42:56 -07002077 }
2078 }
2079 // update the outputs if stopping one with a stream that can affect notification routing
2080 handleNotificationRoutingForStream(stream);
2081 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002082
2083 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2084 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002085 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002086 }
2087
François Gaffiec005e562018-11-06 15:04:49 +01002088 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002089 selectOutputForMusicEffects();
2090 }
Eric Laurente552edb2014-03-10 17:42:56 -07002091 return NO_ERROR;
2092 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002093 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002094 return INVALID_OPERATION;
2095 }
2096}
2097
jiabinbce0c1d2020-10-05 11:20:18 -07002098bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002099{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002100 ALOGV("%s portId %d", __FUNCTION__, portId);
2101
2102 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2103 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002104 // If an output descriptor is closed due to a device routing change,
2105 // then there are race conditions with releaseOutput from tracks
2106 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2107 // destroyed shortly thereafter.
2108 //
2109 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002110 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002111 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002112 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002113
2114 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002115
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302116 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2117 if (outputDesc->isClientActive(client)) {
2118 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2119 stopOutput(portId);
2120 }
2121
Eric Laurent8fc147b2018-07-22 19:13:55 -07002122 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2123 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002124 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002125 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002126 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002127 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002128 if (--outputDesc->mDirectOpenCount == 0) {
2129 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002130 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002131 }
2132 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302133
Andy Hung39efb7a2018-09-26 15:39:28 -07002134 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002135 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2136 // The output is pending reopened to query dynamic profiles and
2137 // there is no active clients
2138 closeOutput(outputDesc->mIoHandle);
2139 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2140 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2141 if (newOutputDesc == nullptr) {
2142 ALOGE("%s failed to open output", __func__);
2143 }
2144 return true;
2145 }
2146 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002147}
2148
Eric Laurentcaf7f482014-11-25 17:50:47 -08002149status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2150 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002151 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002152 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002153 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002154 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002155 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002156 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002157 input_type_t *inputType,
2158 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002159{
François Gaffiec005e562018-11-06 15:04:49 +01002160 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002161 "flags %#x attributes=%s requested device ID %d",
2162 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2163 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002164
Eric Laurentad2e7b92017-09-14 20:06:42 -07002165 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002166 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002167 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002168 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002169 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002170 sp<AudioInputDescriptor> inputDesc;
2171 sp<RecordClientDescriptor> clientDesc;
2172 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002173 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002174 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002175
2176 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2177 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2178 return INVALID_OPERATION;
2179 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002180
Francois Gaffie716e1432019-01-14 16:58:59 +01002181 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2182 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002183 }
2184
Paul McLean466dc8e2015-04-17 13:15:36 -06002185 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01002186 sp<DeviceDescriptor> explicitRoutingDevice =
2187 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002188
Eric Laurentad2e7b92017-09-14 20:06:42 -07002189 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2190 // possible
2191 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2192 *input != AUDIO_IO_HANDLE_NONE) {
2193 ssize_t index = mInputs.indexOfKey(*input);
2194 if (index < 0) {
2195 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2196 status = BAD_VALUE;
2197 goto error;
2198 }
2199 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002200 RecordClientVector clients = inputDesc->getClientsForSession(session);
2201 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002202 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2203 status = BAD_VALUE;
2204 goto error;
2205 }
2206 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2207 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002208 // corresponds to a new client and is only permitted from the same UID.
2209 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002210 if (clients.size() > 1) {
2211 for (const auto& client : clients) {
2212 // The client map is ordered by key values (portId) and portIds are allocated
2213 // incrementaly. So the first client in this list is the one opened by audio flinger
2214 // when the mmap stream is created and should be ignored as it does not correspond
2215 // to an actual client
2216 if (client == *clients.cbegin()) {
2217 continue;
2218 }
2219 if (uid != client->uid() && !client->isSilenced()) {
2220 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2221 uid, client->portId(), client->uid());
2222 status = INVALID_OPERATION;
2223 goto error;
2224 }
Eric Laurent331679c2018-04-16 17:03:16 -07002225 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002226 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002227 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002228 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002229
Eric Laurentfecbceb2021-02-09 14:46:43 +01002230 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002231 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002232 }
2233
2234 *input = AUDIO_IO_HANDLE_NONE;
2235 *inputType = API_INPUT_INVALID;
2236
Francois Gaffie716e1432019-01-14 16:58:59 +01002237 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002238
Francois Gaffie716e1432019-01-14 16:58:59 +01002239 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2240 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2241 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002242 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002243 ALOGW("%s could not find input mix for attr %s",
2244 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002245 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002246 }
jiabinc1de2df2019-05-07 14:26:40 -07002247 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2248 String8(attr->tags + strlen("addr=")),
2249 AUDIO_FORMAT_DEFAULT);
2250 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002251 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002252 __func__, attributes.source, attributes.tags);
2253 status = BAD_VALUE;
2254 goto error;
2255 }
2256
Kevin Rocard25f9b052019-02-27 15:08:54 -08002257 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2258 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2259 } else {
2260 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2261 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002262 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002263 if (explicitRoutingDevice != nullptr) {
2264 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002265 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002266 // Prevent from storing invalid requested device id in clients
2267 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002268 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002269 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2270 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002271 }
François Gaffie11d30102018-11-02 16:09:09 +01002272 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002273 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002274 status = BAD_VALUE;
2275 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002276 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002277 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2278 *inputType = API_INPUT_MIX_CAPTURE;
2279 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002280 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2281 // there is an external policy, but this input is attached to a mix of recorders,
2282 // meaning it receives audio injected into the framework, so the recorder doesn't
2283 // know about it and is therefore considered "legacy"
2284 *inputType = API_INPUT_LEGACY;
2285 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002286 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002287 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002288 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002289 } else {
2290 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002291 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002292
Eric Laurent599c7582015-12-07 18:05:55 -08002293 }
2294
François Gaffiec005e562018-11-06 15:04:49 +01002295 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002296 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002297 status = INVALID_OPERATION;
2298 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002299 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002300
Eric Laurent8f42ea12018-08-08 09:08:25 -07002301exit:
2302
François Gaffiec005e562018-11-06 15:04:49 +01002303 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2304 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002305
Francois Gaffie716e1432019-01-14 16:58:59 +01002306 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002307 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002308 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002309
Mikhail Naganov2996f672019-04-18 12:29:59 -07002310 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002311 requestedDeviceId, attributes.source, flags,
2312 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002313 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002314 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002315
2316 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2317 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002318
Eric Laurent599c7582015-12-07 18:05:55 -08002319 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002320
2321error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002322 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002323}
2324
2325
François Gaffie11d30102018-11-02 16:09:09 +01002326audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002327 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002328 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002329 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002330 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002331 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002332{
2333 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002334 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002335 bool isSoundTrigger = false;
2336
François Gaffiec005e562018-11-06 15:04:49 +01002337 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002338 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2339 if (index >= 0) {
2340 input = mSoundTriggerSessions.valueFor(session);
2341 isSoundTrigger = true;
2342 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2343 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2344 } else {
2345 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002346 }
François Gaffiec005e562018-11-06 15:04:49 +01002347 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002348 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002349 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002350 }
2351
Andy Hungf129b032015-04-07 13:45:50 -07002352 // find a compatible input profile (not necessarily identical in parameters)
2353 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002354 // sampling rate and flags may be updated by getInputProfile
2355 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2356 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002357 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002358 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002359 audio_input_flags_t profileFlags = flags;
2360 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002361 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002362 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002363 profileFlags);
2364 if (profile != 0) {
2365 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002366 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2367 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002368 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2369 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2370 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002371 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2372 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2373 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002374 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002375 }
Eric Laurente552edb2014-03-10 17:42:56 -07002376 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002377 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002378 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002379 if (samplingRate == 0) {
2380 samplingRate = profileSamplingRate;
2381 }
Eric Laurente552edb2014-03-10 17:42:56 -07002382
Eric Laurent322b4d22015-04-03 15:57:54 -07002383 if (profile->getModuleHandle() == 0) {
2384 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002385 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002386 }
2387
Eric Laurentec376dc2021-04-08 20:41:22 +02002388 // Reuse an already opened input if a client with the same session ID already exists
2389 // on that input
2390 for (size_t i = 0; i < mInputs.size(); i++) {
2391 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2392 if (desc->mProfile != profile) {
2393 continue;
2394 }
2395 RecordClientVector clients = desc->clientsList();
2396 for (const auto &client : clients) {
2397 if (session == client->session()) {
2398 return desc->mIoHandle;
2399 }
2400 }
2401 }
2402
Eric Laurent3974e3b2017-12-07 17:58:43 -08002403 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002404 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002405 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002406 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002407 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002408 continue;
2409 }
2410 // if sound trigger, reuse input if used by other sound trigger on same session
2411 // else
2412 // reuse input if active client app is not in IDLE state
2413 //
2414 RecordClientVector clients = desc->clientsList();
2415 bool doClose = false;
2416 for (const auto& client : clients) {
2417 if (isSoundTrigger != client->isSoundTrigger()) {
2418 continue;
2419 }
2420 if (client->isSoundTrigger()) {
2421 if (session == client->session()) {
2422 return desc->mIoHandle;
2423 }
2424 continue;
2425 }
2426 if (client->active() && client->appState() != APP_STATE_IDLE) {
2427 return desc->mIoHandle;
2428 }
2429 doClose = true;
2430 }
2431 if (doClose) {
2432 closeInput(desc->mIoHandle);
2433 } else {
2434 i++;
2435 }
2436 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002437 }
2438
Eric Laurentfe231122017-11-17 17:48:06 -08002439 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002440
Eric Laurentfe231122017-11-17 17:48:06 -08002441 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2442 lConfig.sample_rate = profileSamplingRate;
2443 lConfig.channel_mask = profileChannelMask;
2444 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002445
François Gaffie11d30102018-11-02 16:09:09 +01002446 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002447
2448 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002449 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002450 (profileSamplingRate != lConfig.sample_rate) ||
2451 !audio_formats_match(profileFormat, lConfig.format) ||
2452 (profileChannelMask != lConfig.channel_mask)) {
2453 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002454 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002455 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002456 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002457 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002458 }
Eric Laurent599c7582015-12-07 18:05:55 -08002459 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002460 }
2461
Eric Laurentc722f302014-12-10 11:21:49 -08002462 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002463
Eric Laurent599c7582015-12-07 18:05:55 -08002464 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002465 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002466
Eric Laurent599c7582015-12-07 18:05:55 -08002467 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002468}
2469
Eric Laurent4eb58f12018-12-07 16:41:02 -08002470status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002471{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002472 ALOGV("%s portId %d", __FUNCTION__, portId);
2473
2474 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2475 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002476 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002477 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002478 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002479 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002480 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002481 if (client->active()) {
2482 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2483 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002484 }
2485
Eric Laurent8f42ea12018-08-08 09:08:25 -07002486 audio_session_t session = client->session();
2487
Eric Laurent4eb58f12018-12-07 16:41:02 -08002488 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002489
Eric Laurent4eb58f12018-12-07 16:41:02 -08002490 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002491
Eric Laurent4eb58f12018-12-07 16:41:02 -08002492 status_t status = inputDesc->start();
2493 if (status != NO_ERROR) {
2494 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002495 }
Eric Laurente552edb2014-03-10 17:42:56 -07002496
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002497 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002498 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002499 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002500
Eric Laurent8f42ea12018-08-08 09:08:25 -07002501 // indicate active capture to sound trigger service if starting capture from a mic on
2502 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002503 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002504 if (device != nullptr) {
2505 status = setInputDevice(input, device, true /* force */);
2506 } else {
2507 ALOGW("%s no new input device can be found for descriptor %d",
2508 __FUNCTION__, inputDesc->getId());
2509 status = BAD_VALUE;
2510 }
Eric Laurente552edb2014-03-10 17:42:56 -07002511
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002512 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002513 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002514 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002515 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002516 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2517 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002518 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002519 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002520
François Gaffie11d30102018-11-02 16:09:09 +01002521 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2522 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002523 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002524 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002525 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002526
Eric Laurent8f42ea12018-08-08 09:08:25 -07002527 // automatically enable the remote submix output when input is started if not
2528 // used by a policy mix of type MIX_TYPE_RECORDERS
2529 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002530 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002531 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002532 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002533 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002534 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2535 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002536 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002537 if (address != "") {
2538 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2539 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002540 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002541 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002542 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002543 } else if (status != NO_ERROR) {
2544 // Restore client activity state.
2545 inputDesc->setClientActive(client, false);
2546 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002547 }
2548
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002549 ALOGV("%s input %d source = %d status = %d exit",
2550 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002551
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002552 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002553}
2554
Eric Laurent8fc147b2018-07-22 19:13:55 -07002555status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002556{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002557 ALOGV("%s portId %d", __FUNCTION__, portId);
2558
2559 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2560 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002561 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002562 return BAD_VALUE;
2563 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002564 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002565 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002566 if (!client->active()) {
2567 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002568 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002569 }
Carter Hsue6139d52021-07-08 10:30:20 +08002570 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002571 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002572
Eric Laurent8f42ea12018-08-08 09:08:25 -07002573 inputDesc->stop();
2574 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002575 auto current_source = inputDesc->source();
2576 setInputDevice(input, getNewInputDevice(inputDesc),
2577 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002578 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002579 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002580 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002581 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002582 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2583 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002584 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002585 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002586
2587 // automatically disable the remote submix output when input is stopped if not
2588 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002589 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002590 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002591 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002592 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002593 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2594 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002595 }
2596 if (address != "") {
2597 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2598 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002599 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002600 }
2601 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002602 resetInputDevice(input);
2603
2604 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2605 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002606 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2607 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002608 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002609 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002610 }
2611 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002612 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002613 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002614}
2615
Eric Laurent8fc147b2018-07-22 19:13:55 -07002616void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002617{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002618 ALOGV("%s portId %d", __FUNCTION__, portId);
2619
2620 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2621 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002622 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002623 return;
2624 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002625 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002626 audio_io_handle_t input = inputDesc->mIoHandle;
2627
Eric Laurent8f42ea12018-08-08 09:08:25 -07002628 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002629
Andy Hung39efb7a2018-09-26 15:39:28 -07002630 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002631
Andy Hung39efb7a2018-09-26 15:39:28 -07002632 if (inputDesc->getClientCount() > 0) {
2633 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002634 return;
2635 }
2636
Eric Laurent05b90f82014-08-27 15:32:29 -07002637 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002638 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002639 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002640}
2641
Eric Laurent8f42ea12018-08-08 09:08:25 -07002642void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002643{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002644 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002645
2646 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002647 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002648 }
2649}
2650
Eric Laurent8f42ea12018-08-08 09:08:25 -07002651void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2652{
2653 stopInput(portId);
2654 releaseInput(portId);
2655}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002656
Eric Laurent0dd51852019-04-19 18:18:58 -07002657void AudioPolicyManager::checkCloseInputs() {
2658 // After connecting or disconnecting an input device, close input if:
2659 // - it has no client (was just opened to check profile) OR
2660 // - none of its supported devices are connected anymore OR
2661 // - one of its clients cannot be routed to one of its supported
2662 // devices anymore. Otherwise update device selection
2663 std::vector<audio_io_handle_t> inputsToClose;
2664 for (size_t i = 0; i < mInputs.size(); i++) {
2665 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2666 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002667 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002668 inputsToClose.push_back(mInputs.keyAt(i));
2669 } else {
2670 bool close = false;
2671 for (const auto& client : input->clientsList()) {
2672 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002673 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002674 if (!input->supportedDevices().contains(device)) {
2675 close = true;
2676 break;
2677 }
2678 }
2679 if (close) {
2680 inputsToClose.push_back(mInputs.keyAt(i));
2681 } else {
2682 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2683 }
2684 }
2685 }
2686
2687 for (const audio_io_handle_t handle : inputsToClose) {
2688 ALOGV("%s closing input %d", __func__, handle);
2689 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002690 }
Eric Laurentd4692962014-05-05 18:13:44 -07002691}
2692
François Gaffie251c7f02018-11-07 10:41:08 +01002693void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002694{
2695 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002696 if (indexMin < 0 || indexMax < 0) {
2697 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2698 return;
2699 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002700 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002701
2702 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002703 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2704 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002705 continue;
2706 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002707 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002708 }
Eric Laurente552edb2014-03-10 17:42:56 -07002709}
2710
Eric Laurente0720872014-03-11 09:30:41 -07002711status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002712 int index,
2713 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002714{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002715 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002716 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2717 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2718 return NO_ERROR;
2719 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002720 ALOGV("%s: stream %s attributes=%s", __func__,
2721 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002722 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002723}
2724
Eric Laurente0720872014-03-11 09:30:41 -07002725status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002726 int *index,
2727 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002728{
François Gaffiec005e562018-11-06 15:04:49 +01002729 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2730 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002731 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002732 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002733 deviceTypes = mEngine->getOutputDevicesForStream(
2734 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002735 }
jiabin9a3361e2019-10-01 09:38:30 -07002736 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002737}
2738
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002739status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002740 int index,
2741 audio_devices_t device)
2742{
2743 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002744 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2745 if (group == VOLUME_GROUP_NONE) {
2746 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002747 return BAD_VALUE;
2748 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002749 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002750 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002751 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002752 VolumeSource vs = toVolumeSource(group);
2753 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2754
2755 status = setVolumeCurveIndex(index, device, curves);
2756 if (status != NO_ERROR) {
2757 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2758 return status;
2759 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002760
jiabin9a3361e2019-10-01 09:38:30 -07002761 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002762 auto curCurvAttrs = curves.getAttributes();
2763 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2764 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002765 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002766 } else if (!curves.getStreamTypes().empty()) {
2767 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002768 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002769 } else {
2770 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2771 return BAD_VALUE;
2772 }
jiabin9a3361e2019-10-01 09:38:30 -07002773 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2774 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002775
François Gaffiecfe17322018-11-07 13:41:29 +01002776 // update volume on all outputs and streams matching the following:
2777 // - The requested stream (or a stream matching for volume control) is active on the output
2778 // - The device (or devices) selected by the engine for this stream includes
2779 // the requested device
2780 // - For non default requested device, currently selected device on the output is either the
2781 // requested device or one of the devices selected by the engine for this stream
2782 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2783 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002784 for (size_t i = 0; i < mOutputs.size(); i++) {
2785 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002786 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002787
jiabin9a3361e2019-10-01 09:38:30 -07002788 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2789 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002790 }
François Gaffieed91f582020-01-31 10:35:37 +01002791 if (!(desc->isActive(vs) || isInCall())) {
2792 continue;
2793 }
2794 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2795 curDevices.find(device) == curDevices.end()) {
2796 continue;
2797 }
2798 bool applyVolume = false;
2799 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2800 curSrcDevices.insert(device);
2801 applyVolume = (curSrcDevices.find(
2802 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2803 } else {
2804 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2805 }
2806 if (!applyVolume) {
2807 continue; // next output
2808 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002809 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2810 // If a higher priority strategy is active, and the output is routed to a device with a
2811 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002812 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002813 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002814 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2815 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2816 false /*preferredDevice*/);
2817 if (activeClients.empty()) {
2818 continue;
2819 }
2820 bool isPreempted = false;
2821 bool isHigherPriority = productStrategy < strategy;
2822 for (const auto &client : activeClients) {
2823 if (isHigherPriority && (client->volumeSource() != vs)) {
2824 ALOGV("%s: Strategy=%d (\nrequester:\n"
2825 " group %d, volumeGroup=%d attributes=%s)\n"
2826 " higher priority source active:\n"
2827 " volumeGroup=%d attributes=%s) \n"
2828 " on output %zu, bailing out", __func__, productStrategy,
2829 group, group, toString(attributes).c_str(),
2830 client->volumeSource(), toString(client->attributes()).c_str(), i);
2831 applyVolume = false;
2832 isPreempted = true;
2833 break;
2834 }
2835 // However, continue for loop to ensure no higher prio clients running on output
2836 if (client->volumeSource() == vs) {
2837 applyVolume = true;
2838 }
2839 }
2840 if (isPreempted || applyVolume) {
2841 break;
2842 }
2843 }
2844 if (!applyVolume) {
2845 continue; // next output
2846 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002847 }
François Gaffieed91f582020-01-31 10:35:37 +01002848 //FIXME: workaround for truncated touch sounds
2849 // delayed volume change for system stream to be removed when the problem is
2850 // handled by system UI
2851 status_t volStatus = checkAndSetVolume(
2852 curves, vs, index, desc, curDevices,
2853 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2854 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2855 if (volStatus != NO_ERROR) {
2856 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002857 }
2858 }
François Gaffiecfe17322018-11-07 13:41:29 +01002859 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2860 return status;
2861}
2862
François Gaffieaaac0fd2018-11-22 17:56:39 +01002863status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002864 audio_devices_t device,
2865 IVolumeCurves &volumeCurves)
2866{
2867 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2868 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002869 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2870 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002871 (index > volumeCurves.getVolumeIndexMax())) {
2872 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2873 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2874 return BAD_VALUE;
2875 }
2876 if (!audio_is_output_device(device)) {
2877 return BAD_VALUE;
2878 }
2879
2880 // Force max volume if stream cannot be muted
2881 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2882
François Gaffieaaac0fd2018-11-22 17:56:39 +01002883 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002884 volumeCurves.addCurrentVolumeIndex(device, index);
2885 return NO_ERROR;
2886}
2887
2888status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2889 int &index,
2890 audio_devices_t device)
2891{
2892 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2893 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002894 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002895 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002896 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2897 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002898 }
jiabin9a3361e2019-10-01 09:38:30 -07002899 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002900}
2901
2902status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2903 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002904 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002905{
jiabin9a3361e2019-10-01 09:38:30 -07002906 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002907 return BAD_VALUE;
2908 }
jiabin9a3361e2019-10-01 09:38:30 -07002909 index = curves.getVolumeIndex(deviceTypes);
2910 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002911 return NO_ERROR;
2912}
2913
2914status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2915 int &index)
2916{
2917 index = getVolumeCurves(attr).getVolumeIndexMin();
2918 return NO_ERROR;
2919}
2920
2921status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2922 int &index)
2923{
2924 index = getVolumeCurves(attr).getVolumeIndexMax();
2925 return NO_ERROR;
2926}
2927
Eric Laurent36829f92017-04-07 19:04:42 -07002928audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002929{
2930 // select one output among several suitable for global effects.
2931 // The priority is as follows:
2932 // 1: An offloaded output. If the effect ends up not being offloadable,
2933 // AudioFlinger will invalidate the track and the offloaded output
2934 // will be closed causing the effect to be moved to a PCM output.
2935 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002936 // 3: The primary output
2937 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002938
François Gaffiec005e562018-11-06 15:04:49 +01002939 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2940 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002941 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002942
Eric Laurent36829f92017-04-07 19:04:42 -07002943 if (outputs.size() == 0) {
2944 return AUDIO_IO_HANDLE_NONE;
2945 }
Eric Laurente552edb2014-03-10 17:42:56 -07002946
Eric Laurent36829f92017-04-07 19:04:42 -07002947 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2948 bool activeOnly = true;
2949
2950 while (output == AUDIO_IO_HANDLE_NONE) {
2951 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2952 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2953 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2954
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002955 for (audio_io_handle_t output : outputs) {
2956 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002957 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002958 continue;
2959 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002960 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2961 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002962 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002963 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002964 }
2965 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002966 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002967 }
2968 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002969 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002970 }
2971 }
2972 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2973 output = outputOffloaded;
2974 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2975 output = outputDeepBuffer;
2976 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2977 output = outputPrimary;
2978 } else {
2979 output = outputs[0];
2980 }
2981 activeOnly = false;
2982 }
2983
2984 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002985 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002986 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2987 mMusicEffectOutput = output;
2988 }
2989
2990 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002991 return output;
2992}
2993
Eric Laurent36829f92017-04-07 19:04:42 -07002994audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2995{
2996 return selectOutputForMusicEffects();
2997}
2998
Eric Laurente0720872014-03-11 09:30:41 -07002999status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003000 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003001 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003002 int session,
3003 int id)
3004{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003005 if (session != AUDIO_SESSION_DEVICE) {
3006 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003007 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003008 index = mInputs.indexOfKey(io);
3009 if (index < 0) {
3010 ALOGW("registerEffect() unknown io %d", io);
3011 return INVALID_OPERATION;
3012 }
Eric Laurente552edb2014-03-10 17:42:56 -07003013 }
3014 }
François Gaffiec005e562018-11-06 15:04:49 +01003015 return mEffects.registerEffect(desc, io, session, id,
3016 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
3017 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07003018}
3019
Eric Laurentc241b0d2018-11-28 09:08:49 -08003020status_t AudioPolicyManager::unregisterEffect(int id)
3021{
3022 if (mEffects.getEffect(id) == nullptr) {
3023 return INVALID_OPERATION;
3024 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003025 if (mEffects.isEffectEnabled(id)) {
3026 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3027 setEffectEnabled(id, false);
3028 }
3029 return mEffects.unregisterEffect(id);
3030}
3031
3032status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3033{
3034 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3035 if (effect == nullptr) {
3036 return INVALID_OPERATION;
3037 }
3038
3039 status_t status = mEffects.setEffectEnabled(id, enabled);
3040 if (status == NO_ERROR) {
3041 mInputs.trackEffectEnabled(effect, enabled);
3042 }
3043 return status;
3044}
3045
Eric Laurent6c796322019-04-09 14:13:17 -07003046
3047status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3048{
3049 mEffects.moveEffects(ids, io);
3050 return NO_ERROR;
3051}
3052
Eric Laurentc75307b2015-03-17 15:29:32 -07003053bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3054{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003055 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003056}
3057
3058bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3059{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003060 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003061}
3062
Eric Laurente0720872014-03-11 09:30:41 -07003063bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003064{
3065 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003066 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003067 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003068 return true;
3069 }
3070 }
3071 return false;
3072}
3073
Eric Laurent275e8e92014-11-30 15:14:47 -08003074// Register a list of custom mixes with their attributes and format.
3075// When a mix is registered, corresponding input and output profiles are
3076// added to the remote submix hw module. The profile contains only the
3077// parameters (sampling rate, format...) specified by the mix.
3078// The corresponding input remote submix device is also connected.
3079//
3080// When a remote submix device is connected, the address is checked to select the
3081// appropriate profile and the corresponding input or output stream is opened.
3082//
3083// When capture starts, getInputForAttr() will:
3084// - 1 look for a mix matching the address passed in attribtutes tags if any
3085// - 2 if none found, getDeviceForInputSource() will:
3086// - 2.1 look for a mix matching the attributes source
3087// - 2.2 if none found, default to device selection by policy rules
3088// At this time, the corresponding output remote submix device is also connected
3089// and active playback use cases can be transferred to this mix if needed when reconnecting
3090// after AudioTracks are invalidated
3091//
3092// When playback starts, getOutputForAttr() will:
3093// - 1 look for a mix matching the address passed in attribtutes tags if any
3094// - 2 if none found, look for a mix matching the attributes usage
3095// - 3 if none found, default to device and output selection by policy rules.
3096
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003097status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003098{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003099 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3100 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003101 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003102 sp<HwModule> rSubmixModule;
3103 // examine each mix's route type
3104 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003105 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003106 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3107 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3108 ALOGE("Unsupported Policy Mix %zu of %zu: "
3109 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3110 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003111 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003112 break;
3113 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003114 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3115 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003116 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003117 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3118 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003119 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003120 rSubmixModule = mHwModules.getModuleFromName(
3121 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3122 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003123 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003124 i);
3125 res = INVALID_OPERATION;
3126 break;
3127 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003128 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003129
Eric Laurent97ac8712018-07-27 18:59:02 -07003130 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003131 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003132 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003133 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003134 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3135 } else {
3136 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3137 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003138 }
François Gaffie036e1e92015-03-19 10:16:24 +01003139
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003140 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003141 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003142 res = INVALID_OPERATION;
3143 break;
3144 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003145 audio_config_t outputConfig = mix.mFormat;
3146 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003147 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3148 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003149 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3150 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003151 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003152 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003153 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003154 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003155
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003156 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003157 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3158 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3159 ALOGE("Failed to set remote submix device available, type %u, address %s",
3160 mix.mDeviceType, address.string());
3161 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003162 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003163 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3164 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003165 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003166 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003167 i, mixes.size(), type, address.string());
3168
3169 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3170 mix.mDeviceType, mix.mDeviceAddress,
3171 String8(), AUDIO_FORMAT_DEFAULT);
3172 if (device == nullptr) {
3173 res = INVALID_OPERATION;
3174 break;
3175 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003176
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003177 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003178 // First try to find an already opened output supporting the device
3179 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003180 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003181
Eric Laurentc529cf62020-04-17 18:19:10 -07003182 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003183 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003184 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3185 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003186 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003187 } else {
3188 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003189 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003190 }
3191 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003192 // If no output found, try to find a direct output profile supporting the device
3193 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3194 sp<HwModule> module = mHwModules[i];
3195 for (size_t j = 0;
3196 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3197 j++) {
3198 sp<IOProfile> profile = module->getOutputProfiles()[j];
3199 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3200 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3201 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3202 address.string());
3203 res = INVALID_OPERATION;
3204 } else {
3205 foundOutput = true;
3206 }
3207 }
3208 }
3209 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003210 if (res != NO_ERROR) {
3211 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003212 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003213 res = INVALID_OPERATION;
3214 break;
3215 } else if (!foundOutput) {
3216 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003217 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003218 res = INVALID_OPERATION;
3219 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003220 } else {
3221 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003222 }
Eric Laurentc722f302014-12-10 11:21:49 -08003223 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003224 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003225 if (res != NO_ERROR) {
3226 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003227 } else if (checkOutputs) {
3228 checkForDeviceAndOutputChanges();
3229 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003230 }
3231 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003232}
3233
3234status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3235{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003236 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003237 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003238 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003239 sp<HwModule> rSubmixModule;
3240 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003241 for (const auto& mix : mixes) {
3242 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003243
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003244 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003245 rSubmixModule = mHwModules.getModuleFromName(
3246 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3247 if (rSubmixModule == 0) {
3248 res = INVALID_OPERATION;
3249 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003250 }
3251 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003252
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003253 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003254
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003255 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003256 res = INVALID_OPERATION;
3257 continue;
3258 }
3259
Kevin Rocard04ed0462019-05-02 17:53:24 -07003260 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3261 if (getDeviceConnectionState(device, address.string()) ==
3262 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3263 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3264 address.string(), "remote-submix",
3265 AUDIO_FORMAT_DEFAULT);
3266 if (res != OK) {
3267 ALOGE("Error making RemoteSubmix device unavailable for mix "
3268 "with type %d, address %s", device, address.string());
3269 }
3270 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003271 }
jiabin5740f082019-08-19 15:08:30 -07003272 rSubmixModule->removeOutputProfile(address.c_str());
3273 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003274
Kevin Rocard153f92d2018-12-18 18:33:28 -08003275 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003276 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003277 res = INVALID_OPERATION;
3278 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003279 } else {
3280 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003281 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003282 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003283 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003284 if (res == NO_ERROR && checkOutputs) {
3285 checkForDeviceAndOutputChanges();
3286 updateCallAndOutputRouting();
3287 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003288 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003289}
3290
Mikhail Naganov100f0122018-11-29 11:22:16 -08003291void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3292{
3293 size_t i = 0;
3294 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3295 for (const auto& fmt : mManualSurroundFormats) {
3296 if (i++ != 0) dst->append(", ");
3297 std::string sfmt;
3298 FormatConverter::toString(fmt, sfmt);
3299 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3300 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3301 }
3302}
3303
Eric Laurentc529cf62020-04-17 18:19:10 -07003304// Returns true if all devices types match the predicate and are supported by one HW module
3305bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003306 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003307 std::function<bool(audio_devices_t)> predicate,
3308 const char *context) {
3309 for (size_t i = 0; i < devices.size(); i++) {
3310 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003311 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003312 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003313 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003314 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003315 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003316 return false;
3317 }
3318 }
3319 return true;
3320}
3321
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003322status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003323 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003324 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003325 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3326 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003327 }
3328 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003329 if (res != NO_ERROR) {
3330 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3331 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003332 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003333
3334 checkForDeviceAndOutputChanges();
3335 updateCallAndOutputRouting();
3336
3337 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003338}
3339
3340status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3341 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003342 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3343 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003344 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003345 __FUNCTION__, uid);
3346 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003347 }
3348
Eric Laurentc529cf62020-04-17 18:19:10 -07003349 checkForDeviceAndOutputChanges();
3350 updateCallAndOutputRouting();
3351
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003352 return res;
3353}
3354
Eric Laurent2517af32020-11-25 15:31:27 +01003355
jiabin0a488932020-08-07 17:32:40 -07003356status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3357 device_role_t role,
3358 const AudioDeviceTypeAddrVector &devices) {
3359 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3360 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003361
Eric Laurentc529cf62020-04-17 18:19:10 -07003362 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003363 return BAD_VALUE;
3364 }
jiabin0a488932020-08-07 17:32:40 -07003365 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003366 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003367 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3368 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003369 return status;
3370 }
3371
3372 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003373
3374 bool forceVolumeReeval = false;
3375 // FIXME: workaround for truncated touch sounds
3376 // to be removed when the problem is handled by system UI
3377 uint32_t delayMs = 0;
3378 if (strategy == mCommunnicationStrategy) {
3379 forceVolumeReeval = true;
3380 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3381 updateInputRouting();
3382 }
3383 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003384
3385 return NO_ERROR;
3386}
3387
3388void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3389{
3390 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003391 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003392 // Only apply special touch sound delay once
3393 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003394 }
3395 for (size_t i = 0; i < mOutputs.size(); i++) {
3396 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3397 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3398 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3399 // As done in setDeviceConnectionState, we could also fix default device issue by
3400 // preventing the force re-routing in case of default dev that distinguishes on address.
3401 // Let's give back to engine full device choice decision however.
3402 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003403 // Only apply special touch sound delay once
3404 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003405 }
3406 if (forceVolumeReeval && !newDevices.isEmpty()) {
3407 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3408 }
3409 }
3410}
3411
Eric Laurent2517af32020-11-25 15:31:27 +01003412void AudioPolicyManager::updateInputRouting() {
3413 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303414 // Skip for hotword recording as the input device switch
3415 // is handled within sound trigger HAL
3416 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3417 continue;
3418 }
Eric Laurent2517af32020-11-25 15:31:27 +01003419 auto newDevice = getNewInputDevice(activeDesc);
3420 // Force new input selection if the new device can not be reached via current input
3421 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3422 setInputDevice(activeDesc->mIoHandle, newDevice);
3423 } else {
3424 closeInput(activeDesc->mIoHandle);
3425 }
3426 }
3427}
3428
jiabin0a488932020-08-07 17:32:40 -07003429status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3430 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003431{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003432 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003433
jiabin0a488932020-08-07 17:32:40 -07003434 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003435 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003436 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3437 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003438 return status;
3439 }
3440
3441 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003442
3443 bool forceVolumeReeval = false;
3444 // FIXME: workaround for truncated touch sounds
3445 // to be removed when the problem is handled by system UI
3446 uint32_t delayMs = 0;
3447 if (strategy == mCommunnicationStrategy) {
3448 forceVolumeReeval = true;
3449 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3450 updateInputRouting();
3451 }
3452 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003453
3454 return NO_ERROR;
3455}
3456
jiabin0a488932020-08-07 17:32:40 -07003457status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3458 device_role_t role,
3459 AudioDeviceTypeAddrVector &devices) {
3460 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003461}
3462
Jiabin Huang3b98d322020-09-03 17:54:16 +00003463status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3464 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3465 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3466 dumpAudioDeviceTypeAddrVector(devices).c_str());
3467
Mikhail Naganov55773032020-10-01 15:08:13 -07003468 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003469 return BAD_VALUE;
3470 }
3471 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3472 ALOGW_IF(status != NO_ERROR,
3473 "Engine could not set preferred devices %s for audio source %d role %d",
3474 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3475
3476 return status;
3477}
3478
3479status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3480 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3481 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3482 dumpAudioDeviceTypeAddrVector(devices).c_str());
3483
Mikhail Naganov55773032020-10-01 15:08:13 -07003484 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003485 return BAD_VALUE;
3486 }
3487 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3488 ALOGW_IF(status != NO_ERROR,
3489 "Engine could not add preferred devices %s for audio source %d role %d",
3490 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3491
Eric Laurent2517af32020-11-25 15:31:27 +01003492 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003493 return status;
3494}
3495
3496status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3497 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3498{
3499 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3500 dumpAudioDeviceTypeAddrVector(devices).c_str());
3501
Mikhail Naganov55773032020-10-01 15:08:13 -07003502 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003503 return BAD_VALUE;
3504 }
3505
3506 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3507 audioSource, role, devices);
3508 ALOGW_IF(status != NO_ERROR,
3509 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3510
Eric Laurent2517af32020-11-25 15:31:27 +01003511 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003512 return status;
3513}
3514
3515status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3516 device_role_t role) {
3517 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3518
3519 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3520 ALOGW_IF(status != NO_ERROR,
3521 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3522
Eric Laurent2517af32020-11-25 15:31:27 +01003523 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003524 return status;
3525}
3526
3527status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3528 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3529 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3530}
3531
Oscar Azucena90e77632019-11-27 17:12:28 -08003532status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003533 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003534 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003535 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3536 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003537 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003538 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3539 if (status != NO_ERROR) {
3540 ALOGE("%s() could not set device affinity for userId %d",
3541 __FUNCTION__, userId);
3542 return status;
3543 }
3544
3545 // reevaluate outputs for all devices
3546 checkForDeviceAndOutputChanges();
3547 updateCallAndOutputRouting();
3548
3549 return NO_ERROR;
3550}
3551
3552status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003553 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003554 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3555 if (status != NO_ERROR) {
3556 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3557 __FUNCTION__, userId);
3558 return status;
3559 }
3560
3561 // reevaluate outputs for all devices
3562 checkForDeviceAndOutputChanges();
3563 updateCallAndOutputRouting();
3564
3565 return NO_ERROR;
3566}
3567
Andy Hungc29d82b2018-10-05 12:23:17 -07003568void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003569{
Andy Hungc29d82b2018-10-05 12:23:17 -07003570 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3571 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003572 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003573 std::string stateLiteral;
3574 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003575 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003576 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3577 "communications", "media", "record", "dock", "system",
3578 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3579 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3580 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003581 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3582 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3583 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3584 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3585 dst->append(" (MANUAL: ");
3586 dumpManualSurroundFormats(dst);
3587 dst->append(")");
3588 }
3589 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003590 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003591 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3592 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003593 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003594 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003595
Andy Hungc29d82b2018-10-05 12:23:17 -07003596 mAvailableOutputDevices.dump(dst, String8("Available output"));
3597 mAvailableInputDevices.dump(dst, String8("Available input"));
3598 mHwModulesAll.dump(dst);
3599 mOutputs.dump(dst);
3600 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003601 mEffects.dump(dst);
3602 mAudioPatches.dump(dst);
3603 mPolicyMixes.dump(dst);
3604 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003605
Kevin Rocardb99cc752019-03-21 20:52:24 -07003606 dst->appendFormat(" AllowedCapturePolicies:\n");
3607 for (auto& policy : mAllowedCapturePolicies) {
3608 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3609 }
3610
François Gaffiec005e562018-11-06 15:04:49 +01003611 dst->appendFormat("\nPolicy Engine dump:\n");
3612 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003613}
3614
3615status_t AudioPolicyManager::dump(int fd)
3616{
3617 String8 result;
3618 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003619 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003620 return NO_ERROR;
3621}
3622
Kevin Rocardb99cc752019-03-21 20:52:24 -07003623status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3624{
3625 mAllowedCapturePolicies[uid] = capturePolicy;
3626 return NO_ERROR;
3627}
3628
Eric Laurente552edb2014-03-10 17:42:56 -07003629// This function checks for the parameters which can be offloaded.
3630// This can be enhanced depending on the capability of the DSP and policy
3631// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003632audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003633{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003634 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003635 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003636 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003637 offloadInfo.format,
3638 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3639 offloadInfo.has_video);
3640
Andy Hung2ddee192015-12-18 17:34:44 -08003641 if (mMasterMono) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003642 return AUDIO_OFFLOAD_NOT_SUPPORTED; // no offloading if mono is set.
Andy Hung2ddee192015-12-18 17:34:44 -08003643 }
3644
Eric Laurente552edb2014-03-10 17:42:56 -07003645 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003646 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003647 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3648 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003649 }
3650
3651 // Check if stream type is music, then only allow offload as of now.
3652 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3653 {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003654 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3655 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003656 }
3657
3658 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003659 const bool allowOffloadWithVideo =
3660 property_get_bool("audio.offload.video", false /* default_value */);
3661 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003662 ALOGV("%s: has_video == true, returning false", __func__);
3663 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003664 }
3665
3666 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003667 const int min_duration_secs = property_get_int32(
3668 "audio.offload.min.duration.secs", -1 /* default_value */);
3669 if (min_duration_secs >= 0) {
3670 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003671 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3672 __func__, min_duration_secs);
3673 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003674 }
3675 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003676 ALOGV("%s: Offload denied by duration < default min(=%u)",
3677 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3678 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003679 }
3680
3681 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3682 // creating an offloaded track and tearing it down immediately after start when audioflinger
3683 // detects there is an active non offloadable effect.
3684 // FIXME: We should check the audio session here but we do not have it in this context.
3685 // This may prevent offloading in rare situations where effects are left active by apps
3686 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003687 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003688 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003689 }
3690
3691 // See if there is a profile to support this.
3692 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003693 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003694 offloadInfo.sample_rate,
3695 offloadInfo.format,
3696 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003697 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3698 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003699 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3700 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3701 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003702 if (profile == nullptr) {
3703 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3704 }
3705 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3706 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3707 }
3708 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003709}
3710
Michael Chana94fbb22018-04-24 14:31:19 +10003711bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3712 const audio_attributes_t& attributes) {
3713 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003714 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003715 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003716 config.sample_rate,
3717 config.format,
3718 config.channel_mask,
3719 output_flags,
3720 true /* directOnly */);
3721 ALOGV("%s() profile %sfound with name: %s, "
3722 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3723 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003724 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003725 config.sample_rate, config.format, config.channel_mask, output_flags);
3726 return (profile != 0);
3727}
3728
Eric Laurent6a94d692014-05-20 11:18:06 -07003729status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3730 audio_port_type_t type,
3731 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003732 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003733 unsigned int *generation)
3734{
jiabin19cdba52020-11-24 11:28:58 -08003735 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3736 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003737 return BAD_VALUE;
3738 }
3739 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003740 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003741 *num_ports = 0;
3742 }
3743
3744 size_t portsWritten = 0;
3745 size_t portsMax = *num_ports;
3746 *num_ports = 0;
3747 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003748 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3749 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003750 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003751 for (const auto& dev : mAvailableOutputDevices) {
3752 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003753 continue;
3754 }
3755 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003756 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003757 }
3758 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003759 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003760 }
3761 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003762 for (const auto& dev : mAvailableInputDevices) {
3763 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003764 continue;
3765 }
3766 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003767 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003768 }
3769 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003770 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003771 }
3772 }
3773 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3774 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3775 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3776 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3777 }
3778 *num_ports += mInputs.size();
3779 }
3780 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003781 size_t numOutputs = 0;
3782 for (size_t i = 0; i < mOutputs.size(); i++) {
3783 if (!mOutputs[i]->isDuplicated()) {
3784 numOutputs++;
3785 if (portsWritten < portsMax) {
3786 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3787 }
3788 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003789 }
Eric Laurent84c70242014-06-23 08:46:27 -07003790 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003791 }
3792 }
3793 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003794 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003795 return NO_ERROR;
3796}
3797
jiabin19cdba52020-11-24 11:28:58 -08003798status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003799{
Eric Laurent99fcae42018-05-17 16:59:18 -07003800 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3801 return BAD_VALUE;
3802 }
3803 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3804 if (dev != 0) {
3805 dev->toAudioPort(port);
3806 return NO_ERROR;
3807 }
3808 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3809 if (dev != 0) {
3810 dev->toAudioPort(port);
3811 return NO_ERROR;
3812 }
3813 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3814 if (out != 0) {
3815 out->toAudioPort(port);
3816 return NO_ERROR;
3817 }
3818 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3819 if (in != 0) {
3820 in->toAudioPort(port);
3821 return NO_ERROR;
3822 }
3823 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003824}
3825
François Gaffieafd4cea2019-11-18 15:50:22 +01003826status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3827 audio_patch_handle_t *handle,
3828 uid_t uid, uint32_t delayMs,
3829 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003830{
François Gaffieafd4cea2019-11-18 15:50:22 +01003831 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003832 if (handle == NULL || patch == NULL) {
3833 return BAD_VALUE;
3834 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003835 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003836
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003837 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003838 return BAD_VALUE;
3839 }
3840 // only one source per audio patch supported for now
3841 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003842 return INVALID_OPERATION;
3843 }
Eric Laurent874c42872014-08-08 15:13:39 -07003844
3845 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003846 return INVALID_OPERATION;
3847 }
Eric Laurent874c42872014-08-08 15:13:39 -07003848 for (size_t i = 0; i < patch->num_sinks; i++) {
3849 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3850 return INVALID_OPERATION;
3851 }
3852 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003853
3854 sp<AudioPatch> patchDesc;
3855 ssize_t index = mAudioPatches.indexOfKey(*handle);
3856
François Gaffieafd4cea2019-11-18 15:50:22 +01003857 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3858 patch->sources[0].role,
3859 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003860#if LOG_NDEBUG == 0
3861 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003862 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3863 patch->sinks[i].role,
3864 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003865 }
3866#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003867
3868 if (index >= 0) {
3869 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003870 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3871 __func__, mUidCached, patchDesc->getUid(), uid);
3872 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003873 return INVALID_OPERATION;
3874 }
3875 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003876 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003877 }
3878
3879 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003880 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003881 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003882 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003883 return BAD_VALUE;
3884 }
Eric Laurent84c70242014-06-23 08:46:27 -07003885 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3886 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003887 if (patchDesc != 0) {
3888 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003889 ALOGV("%s source id differs for patch current id %d new id %d",
3890 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003891 return BAD_VALUE;
3892 }
3893 }
Eric Laurent874c42872014-08-08 15:13:39 -07003894 DeviceVector devices;
3895 for (size_t i = 0; i < patch->num_sinks; i++) {
3896 // Only support mix to devices connection
3897 // TODO add support for mix to mix connection
3898 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003899 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003900 return INVALID_OPERATION;
3901 }
3902 sp<DeviceDescriptor> devDesc =
3903 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3904 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003905 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003906 return BAD_VALUE;
3907 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003908
François Gaffie11d30102018-11-02 16:09:09 +01003909 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003910 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003911 NULL, // updatedSamplingRate
3912 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003913 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003914 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003915 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003916 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003917 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003918 return INVALID_OPERATION;
3919 }
3920 devices.add(devDesc);
3921 }
3922 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003923 return INVALID_OPERATION;
3924 }
Eric Laurent874c42872014-08-08 15:13:39 -07003925
Eric Laurent6a94d692014-05-20 11:18:06 -07003926 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003927 ALOGV("%s setting device %s on output %d",
3928 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003929 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003930 index = mAudioPatches.indexOfKey(*handle);
3931 if (index >= 0) {
3932 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003933 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003934 }
3935 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003936 patchDesc->setUid(uid);
3937 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003938 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003939 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003940 return INVALID_OPERATION;
3941 }
3942 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3943 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3944 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003945 // only one sink supported when connecting an input device to a mix
3946 if (patch->num_sinks > 1) {
3947 return INVALID_OPERATION;
3948 }
François Gaffie53615e22015-03-19 09:24:12 +01003949 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003950 if (inputDesc == NULL) {
3951 return BAD_VALUE;
3952 }
3953 if (patchDesc != 0) {
3954 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3955 return BAD_VALUE;
3956 }
3957 }
François Gaffie11d30102018-11-02 16:09:09 +01003958 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003959 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003960 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003961 return BAD_VALUE;
3962 }
3963
François Gaffie11d30102018-11-02 16:09:09 +01003964 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003965 patch->sinks[0].sample_rate,
3966 NULL, /*updatedSampleRate*/
3967 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003968 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003969 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003970 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003971 // FIXME for the parameter type,
3972 // and the NONE
3973 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003974 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003975 return INVALID_OPERATION;
3976 }
3977 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003978 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003979 device->toString().c_str(), inputDesc->mIoHandle);
3980 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003981 index = mAudioPatches.indexOfKey(*handle);
3982 if (index >= 0) {
3983 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003984 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003985 }
3986 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003987 patchDesc->setUid(uid);
3988 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003989 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003990 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003991 return INVALID_OPERATION;
3992 }
3993 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3994 // device to device connection
3995 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003996 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003997 return BAD_VALUE;
3998 }
3999 }
François Gaffie11d30102018-11-02 16:09:09 +01004000 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004001 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004002 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004003 return BAD_VALUE;
4004 }
Eric Laurent874c42872014-08-08 15:13:39 -07004005
Eric Laurent6a94d692014-05-20 11:18:06 -07004006 //update source and sink with our own data as the data passed in the patch may
4007 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004008 PatchBuilder patchBuilder;
4009 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004010
4011 // if first sink is to MSD, establish single MSD patch
4012 if (getMsdAudioOutDevices().contains(
4013 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4014 ALOGV("%s patching to MSD", __FUNCTION__);
4015 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4016 goto installPatch;
4017 }
4018
François Gaffieafd4cea2019-11-18 15:50:22 +01004019 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4020 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004021
Eric Laurent874c42872014-08-08 15:13:39 -07004022 for (size_t i = 0; i < patch->num_sinks; i++) {
4023 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004024 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004025 return INVALID_OPERATION;
4026 }
François Gaffie11d30102018-11-02 16:09:09 +01004027 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004028 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004029 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004030 return BAD_VALUE;
4031 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004032 audio_port_config sinkPortConfig = {};
4033 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4034 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004035
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004036 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4037 // volume management purpose (tracking activity)
4038 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4039 // in config XML to reach the sink so that is can be declared as available.
4040 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4041 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4042 if (sourceDesc != nullptr) {
4043 // take care of dynamic routing for SwOutput selection,
4044 audio_attributes_t attributes = sourceDesc->attributes();
4045 audio_stream_type_t stream = sourceDesc->stream();
4046 audio_attributes_t resultAttr;
4047 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4048 config.sample_rate = sourceDesc->config().sample_rate;
4049 config.channel_mask = sourceDesc->config().channel_mask;
4050 config.format = sourceDesc->config().format;
4051 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4052 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4053 bool isRequestedDeviceForExclusiveUse = false;
4054 output_type_t outputType;
4055 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4056 &stream, sourceDesc->uid(), &config, &flags,
4057 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4058 nullptr, &outputType);
4059 if (output == AUDIO_IO_HANDLE_NONE) {
4060 ALOGV("%s no output for device %s",
4061 __FUNCTION__, sinkDevice->toString().c_str());
4062 return INVALID_OPERATION;
4063 }
4064 outputDesc = mOutputs.valueFor(output);
4065 if (outputDesc->isDuplicated()) {
4066 ALOGE("%s output is duplicated", __func__);
4067 return INVALID_OPERATION;
4068 }
4069 sourceDesc->setSwOutput(outputDesc);
4070 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004071 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004072 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004073 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004074 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01004075 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
4076 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004077 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4078 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004079 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
4080 (sourceDesc != nullptr &&
4081 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004082 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004083 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004084 return INVALID_OPERATION;
4085 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004086 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004087 SortedVector<audio_io_handle_t> outputs =
4088 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4089 // if the sink device is reachable via an opened output stream, request to
4090 // go via this output stream by adding a second source to the patch
4091 // description
4092 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004093 if (output != AUDIO_IO_HANDLE_NONE) {
4094 outputDesc = mOutputs.valueFor(output);
4095 if (outputDesc->isDuplicated()) {
4096 ALOGV("%s output for device %s is duplicated",
4097 __FUNCTION__, sinkDevice->toString().c_str());
4098 return INVALID_OPERATION;
4099 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004100 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004101 }
4102 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004103 audio_port_config srcMixPortConfig = {};
4104 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
François Gaffieafd4cea2019-11-18 15:50:22 +01004105 // for volume control, we may need a valid stream
4106 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
4107 sourceDesc->stream() : AUDIO_STREAM_PATCH;
4108 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004109 }
Eric Laurent83b88082014-06-20 18:31:16 -07004110 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004111 }
4112 // TODO: check from routing capabilities in config file and other conflicting patches
4113
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004114installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004115 status_t status = installPatch(
4116 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004117 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004118 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004119 return INVALID_OPERATION;
4120 }
4121 } else {
4122 return BAD_VALUE;
4123 }
4124 } else {
4125 return BAD_VALUE;
4126 }
4127 return NO_ERROR;
4128}
4129
4130status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4131 uid_t uid)
4132{
4133 ALOGV("releaseAudioPatch() patch %d", handle);
4134
4135 ssize_t index = mAudioPatches.indexOfKey(handle);
4136
4137 if (index < 0) {
4138 return BAD_VALUE;
4139 }
4140 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004141 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4142 __func__, mUidCached, patchDesc->getUid(), uid);
4143 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004144 return INVALID_OPERATION;
4145 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004146 return releaseAudioPatchInternal(handle);
4147}
Eric Laurent6a94d692014-05-20 11:18:06 -07004148
François Gaffieafd4cea2019-11-18 15:50:22 +01004149status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4150 uint32_t delayMs)
4151{
4152 ALOGV("%s patch %d", __func__, handle);
4153 if (mAudioPatches.indexOfKey(handle) < 0) {
4154 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4155 return BAD_VALUE;
4156 }
4157 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004158 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004159 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004160 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004161 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004162 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004163 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004164 return BAD_VALUE;
4165 }
4166
François Gaffie11d30102018-11-02 16:09:09 +01004167 setOutputDevices(outputDesc,
4168 getNewOutputDevices(outputDesc, true /*fromCache*/),
4169 true,
4170 0,
4171 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004172 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4173 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004174 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004175 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004176 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004177 return BAD_VALUE;
4178 }
4179 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004180 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004181 true,
4182 NULL);
4183 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004184 status_t status =
4185 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4186 ALOGV("%s patch panel returned %d patchHandle %d",
4187 __func__, status, patchDesc->getAfHandle());
4188 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004189 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004190 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004191 // SW Bridge
4192 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4193 sp<SwAudioOutputDescriptor> outputDesc =
4194 mOutputs.getOutputFromId(patch->sources[1].id);
4195 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004196 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4197 // releaseOutput has already called closeOuput in case of direct output
4198 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004199 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004200 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4201 // force SwOutput patch removal as AF counter part patch has already gone.
4202 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4203 removeAudioPatch(outputDesc->getPatchHandle());
4204 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004205 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4206 setOutputDevices(outputDesc,
4207 getNewOutputDevices(outputDesc, true /*fromCache*/),
4208 true, /*force*/
4209 0,
4210 NULL);
4211 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004212 } else {
4213 return BAD_VALUE;
4214 }
4215 } else {
4216 return BAD_VALUE;
4217 }
4218 return NO_ERROR;
4219}
4220
4221status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4222 struct audio_patch *patches,
4223 unsigned int *generation)
4224{
François Gaffie53615e22015-03-19 09:24:12 +01004225 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004226 return BAD_VALUE;
4227 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004228 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004229 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004230}
4231
Eric Laurente1715a42014-05-20 11:30:42 -07004232status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004233{
Eric Laurente1715a42014-05-20 11:30:42 -07004234 ALOGV("setAudioPortConfig()");
4235
4236 if (config == NULL) {
4237 return BAD_VALUE;
4238 }
4239 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4240 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004241 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4242 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004243 }
4244
Eric Laurenta121f902014-06-03 13:32:54 -07004245 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004246 if (config->type == AUDIO_PORT_TYPE_MIX) {
4247 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004248 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004249 if (outputDesc == NULL) {
4250 return BAD_VALUE;
4251 }
Eric Laurent84c70242014-06-23 08:46:27 -07004252 ALOG_ASSERT(!outputDesc->isDuplicated(),
4253 "setAudioPortConfig() called on duplicated output %d",
4254 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004255 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004256 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004257 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004258 if (inputDesc == NULL) {
4259 return BAD_VALUE;
4260 }
Eric Laurenta121f902014-06-03 13:32:54 -07004261 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004262 } else {
4263 return BAD_VALUE;
4264 }
4265 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4266 sp<DeviceDescriptor> deviceDesc;
4267 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4268 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4269 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4270 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4271 } else {
4272 return BAD_VALUE;
4273 }
4274 if (deviceDesc == NULL) {
4275 return BAD_VALUE;
4276 }
Eric Laurenta121f902014-06-03 13:32:54 -07004277 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004278 } else {
4279 return BAD_VALUE;
4280 }
4281
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004282 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004283 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4284 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004285 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004286 audioPortConfig->toAudioPortConfig(&newConfig, config);
4287 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004288 }
Eric Laurenta121f902014-06-03 13:32:54 -07004289 if (status != NO_ERROR) {
4290 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004291 }
Eric Laurente1715a42014-05-20 11:30:42 -07004292
4293 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004294}
4295
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004296void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4297{
Eric Laurentd60560a2015-04-10 11:31:20 -07004298 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004299 clearAudioPatches(uid);
4300 clearSessionRoutes(uid);
4301}
4302
Eric Laurent6a94d692014-05-20 11:18:06 -07004303void AudioPolicyManager::clearAudioPatches(uid_t uid)
4304{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004305 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004306 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004307 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004308 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004309 }
4310 }
4311}
4312
François Gaffiec005e562018-11-06 15:04:49 +01004313void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004314{
François Gaffiec005e562018-11-06 15:04:49 +01004315 // Take the first attributes following the product strategy as it is used to retrieve the routed
4316 // device. All attributes wihin a strategy follows the same "routing strategy"
4317 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4318 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004319 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004320 for (size_t j = 0; j < mOutputs.size(); j++) {
4321 if (mOutputs.keyAt(j) == ouptutToSkip) {
4322 continue;
4323 }
4324 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004325 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004326 continue;
4327 }
4328 // If the default device for this strategy is on another output mix,
4329 // invalidate all tracks in this strategy to force re connection.
4330 // Otherwise select new device on the output mix.
4331 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004332 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4333 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004334 }
4335 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004336 setOutputDevices(
4337 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004338 }
4339 }
4340}
4341
4342void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4343{
4344 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004345 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004346 for (size_t i = 0; i < mOutputs.size(); i++) {
4347 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004348 for (const auto& client : outputDesc->getClientIterable()) {
4349 if (client->hasPreferredDevice() && client->uid() == uid) {
4350 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004351 auto clientStrategy = client->strategy();
4352 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4353 end(affectedStrategies)) {
4354 continue;
4355 }
4356 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004357 }
4358 }
4359 }
4360 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004361 for (const auto& strategy : affectedStrategies) {
4362 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004363 }
4364
4365 // remove input routes associated with this uid
4366 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004367 for (size_t i = 0; i < mInputs.size(); i++) {
4368 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004369 for (const auto& client : inputDesc->getClientIterable()) {
4370 if (client->hasPreferredDevice() && client->uid() == uid) {
4371 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4372 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004373 }
4374 }
4375 }
4376 // reroute inputs if necessary
4377 SortedVector<audio_io_handle_t> inputsToClose;
4378 for (size_t i = 0; i < mInputs.size(); i++) {
4379 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004380 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004381 inputsToClose.add(inputDesc->mIoHandle);
4382 }
4383 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004384 for (const auto& input : inputsToClose) {
4385 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004386 }
4387}
4388
Eric Laurentd60560a2015-04-10 11:31:20 -07004389void AudioPolicyManager::clearAudioSources(uid_t uid)
4390{
4391 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004392 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4393 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004394 stopAudioSource(mAudioSources.keyAt(i));
4395 }
4396 }
4397}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004398
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004399status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4400 audio_io_handle_t *ioHandle,
4401 audio_devices_t *device)
4402{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004403 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4404 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004405 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004406 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004407
François Gaffiedf372692015-03-19 10:43:27 +01004408 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004409}
4410
Eric Laurentd60560a2015-04-10 11:31:20 -07004411status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004412 const audio_attributes_t *attributes,
4413 audio_port_handle_t *portId,
4414 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004415{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004416 ALOGV("%s", __FUNCTION__);
4417 *portId = AUDIO_PORT_HANDLE_NONE;
4418
4419 if (source == NULL || attributes == NULL || portId == NULL) {
4420 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4421 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004422 return BAD_VALUE;
4423 }
4424
Eric Laurentd60560a2015-04-10 11:31:20 -07004425 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4426 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004427 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4428 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004429 return INVALID_OPERATION;
4430 }
4431
François Gaffie11d30102018-11-02 16:09:09 +01004432 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004433 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004434 String8(source->ext.device.address),
4435 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004436 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004437 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004438 return BAD_VALUE;
4439 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004440
jiabin4ef93452019-09-10 14:29:54 -07004441 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004442
François Gaffieaaac0fd2018-11-22 17:56:39 +01004443 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004444 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004445 mEngine->getStreamTypeForAttributes(*attributes),
4446 mEngine->getProductStrategyForAttributes(*attributes),
4447 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004448
4449 status_t status = connectAudioSource(sourceDesc);
4450 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004451 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004452 }
4453 return status;
4454}
4455
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004456status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004457{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004458 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004459
4460 // make sure we only have one patch per source.
4461 disconnectAudioSource(sourceDesc);
4462
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004463 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004464 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4465 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4466 sourceDesc->srcDevice()->type(),
4467 String8(sourceDesc->srcDevice()->address().c_str()),
4468 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004469 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004470 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004471 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004472 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004473 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4474 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4475 return INVALID_OPERATION;
4476 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004477 PatchBuilder patchBuilder;
4478 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4479 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4480 status_t status =
4481 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4482 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4483 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4484 return INVALID_OPERATION;
4485 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004486 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004487 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4488 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4489 if (swOutput != 0) {
4490 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004491 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004492 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004493 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004494 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004495 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004496 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004497 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004498 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004499 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004500 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004501 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004502 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4503 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004504 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004505 if (delayMs != 0) {
4506 usleep(delayMs * 1000);
4507 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004508 } else {
4509 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4510 if (hwOutputDesc != 0) {
4511 // create Hwoutput and add to mHwOutputs
4512 } else {
4513 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4514 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004515 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004516 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004517
4518FailureSourceActive:
4519 swOutput->stop();
4520 releaseOutput(sourceDesc->portId());
4521FailureSourceAdded:
4522 sourceDesc->setSwOutput(nullptr);
4523FailureReleasePatch:
4524 releaseAudioPatchInternal(handle);
4525 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004526}
4527
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004528status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004529{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004530 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4531 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004532 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004533 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004534 return BAD_VALUE;
4535 }
4536 status_t status = disconnectAudioSource(sourceDesc);
4537
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004538 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004539 return status;
4540}
4541
Andy Hung2ddee192015-12-18 17:34:44 -08004542status_t AudioPolicyManager::setMasterMono(bool mono)
4543{
4544 if (mMasterMono == mono) {
4545 return NO_ERROR;
4546 }
4547 mMasterMono = mono;
4548 // if enabling mono we close all offloaded devices, which will invalidate the
4549 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4550 // for recreating the new AudioTrack as non-offloaded PCM.
4551 //
4552 // If disabling mono, we leave all tracks as is: we don't know which clients
4553 // and tracks are able to be recreated as offloaded. The next "song" should
4554 // play back offloaded.
4555 if (mMasterMono) {
4556 Vector<audio_io_handle_t> offloaded;
4557 for (size_t i = 0; i < mOutputs.size(); ++i) {
4558 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4559 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4560 offloaded.push(desc->mIoHandle);
4561 }
4562 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004563 for (const auto& handle : offloaded) {
4564 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004565 }
4566 }
4567 // update master mono for all remaining outputs
4568 for (size_t i = 0; i < mOutputs.size(); ++i) {
4569 updateMono(mOutputs.keyAt(i));
4570 }
4571 return NO_ERROR;
4572}
4573
4574status_t AudioPolicyManager::getMasterMono(bool *mono)
4575{
4576 *mono = mMasterMono;
4577 return NO_ERROR;
4578}
4579
Eric Laurentac9cef52017-06-09 15:46:26 -07004580float AudioPolicyManager::getStreamVolumeDB(
4581 audio_stream_type_t stream, int index, audio_devices_t device)
4582{
jiabin9a3361e2019-10-01 09:38:30 -07004583 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004584}
4585
jiabin81772902018-04-02 17:52:27 -07004586status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4587 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004588 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004589{
Kriti Dang6537def2021-03-02 13:46:59 +01004590 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4591 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004592 return BAD_VALUE;
4593 }
Kriti Dang6537def2021-03-02 13:46:59 +01004594 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4595 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004596
4597 size_t formatsWritten = 0;
4598 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004599
Kriti Dang6537def2021-03-02 13:46:59 +01004600 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004601 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4602 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004603 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07004604 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01004605 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004606 bool formatEnabled = true;
4607 switch (forceUse) {
4608 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01004609 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004610 break;
4611 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4612 formatEnabled = false;
4613 break;
4614 default: // AUTO or ALWAYS => true
4615 break;
jiabin81772902018-04-02 17:52:27 -07004616 }
4617 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4618 }
jiabin81772902018-04-02 17:52:27 -07004619 }
4620 return NO_ERROR;
4621}
4622
Kriti Dang6537def2021-03-02 13:46:59 +01004623status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
4624 audio_format_t *surroundFormats) {
4625 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
4626 return BAD_VALUE;
4627 }
4628 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
4629 __func__, *numSurroundFormats, surroundFormats);
4630
4631 size_t formatsWritten = 0;
4632 size_t formatsMax = *numSurroundFormats;
4633 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4634
4635 // Return formats from all device profiles that have already been resolved by
4636 // checkOutputsForDevice().
4637 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4638 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4639 audio_devices_t deviceType = device->type();
4640 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4641 // returns formats reported by HDMI devices.
4642 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4643 continue;
4644 }
4645 // Formats reported by sink devices
4646 std::unordered_set<audio_format_t> formatset;
4647 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4648 formatset.insert(it->second.begin(), it->second.end());
4649 }
4650
4651 // Formats hard-coded in the in policy configuration file (if any).
4652 FormatVector encodedFormats = device->encodedFormats();
4653 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4654 // Filter the formats which are supported by the vendor hardware.
4655 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4656 if (mConfig.getSurroundFormats().count(*it) != 0) {
4657 formats.insert(*it);
4658 } else {
4659 for (const auto& pair : mConfig.getSurroundFormats()) {
4660 if (pair.second.count(*it) != 0) {
4661 formats.insert(pair.first);
4662 break;
4663 }
4664 }
4665 }
4666 }
4667 }
4668 *numSurroundFormats = formats.size();
4669 for (const auto& format: formats) {
4670 if (formatsWritten < formatsMax) {
4671 surroundFormats[formatsWritten++] = format;
4672 }
4673 }
4674 return NO_ERROR;
4675}
4676
jiabin81772902018-04-02 17:52:27 -07004677status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4678{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004679 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004680 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4681 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004682 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004683 return BAD_VALUE;
4684 }
4685
Mikhail Naganov100f0122018-11-29 11:22:16 -08004686 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4687 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004688 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004689 return INVALID_OPERATION;
4690 }
4691
Mikhail Naganov100f0122018-11-29 11:22:16 -08004692 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004693 return NO_ERROR;
4694 }
4695
Mikhail Naganov100f0122018-11-29 11:22:16 -08004696 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004697 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004698 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004699 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004700 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004701 }
4702 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004703 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004704 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004705 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004706 }
4707 }
4708
4709 sp<SwAudioOutputDescriptor> outputDesc;
4710 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004711 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4712 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004713 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4714 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004715 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004716 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004717 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4718 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4719 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004720 name.c_str(),
4721 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004722 if (status != NO_ERROR) {
4723 continue;
4724 }
4725 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4726 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4727 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004728 name.c_str(),
4729 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004730 profileUpdated |= (status == NO_ERROR);
4731 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004732 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004733 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004734 AUDIO_DEVICE_IN_HDMI);
4735 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4736 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004737 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004738 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004739 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4740 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4741 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004742 name.c_str(),
4743 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004744 if (status != NO_ERROR) {
4745 continue;
4746 }
4747 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4748 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4749 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004750 name.c_str(),
4751 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004752 profileUpdated |= (status == NO_ERROR);
4753 }
4754
jiabin81772902018-04-02 17:52:27 -07004755 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004756 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004757 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004758 }
4759
4760 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4761}
4762
Eric Laurent5ada82e2019-08-29 17:53:54 -07004763void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004764{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004765 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004766 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004767 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004768 }
4769}
4770
jiabin6012f912018-11-02 17:06:30 -07004771bool AudioPolicyManager::isHapticPlaybackSupported()
4772{
4773 for (const auto& hwModule : mHwModules) {
4774 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4775 for (const auto &outProfile : outputProfiles) {
4776 struct audio_port audioPort;
4777 outProfile->toAudioPort(&audioPort);
4778 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4779 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4780 return true;
4781 }
4782 }
4783 }
4784 }
4785 return false;
4786}
4787
Eric Laurent8340e672019-11-06 11:01:08 -08004788bool AudioPolicyManager::isCallScreenModeSupported()
4789{
4790 return getConfig().isCallScreenModeSupported();
4791}
4792
4793
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004794status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004795{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004796 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004797 if (!sourceDesc->isConnected()) {
4798 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
4799 return NO_ERROR;
4800 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004801 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4802 if (swOutput != 0) {
4803 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004804 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004805 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004806 }
jiabinbce0c1d2020-10-05 11:20:18 -07004807 if (releaseOutput(sourceDesc->portId())) {
4808 // The output descriptor is reopened to query dynamic profiles. In that case, there is
4809 // no need to release audio patch here but just return NO_ERROR.
4810 return NO_ERROR;
4811 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004812 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004813 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004814 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004815 // close Hwoutput and remove from mHwOutputs
4816 } else {
4817 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4818 }
4819 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004820 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
4821 sourceDesc->disconnect();
4822 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07004823}
4824
François Gaffiec005e562018-11-06 15:04:49 +01004825sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4826 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004827{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004828 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004829 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004830 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004831 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004832 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4833 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004834 source = sourceDesc;
4835 break;
4836 }
4837 }
4838 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004839}
4840
Eric Laurent39095982021-08-24 18:29:27 +02004841/* static */
4842bool AudioPolicyManager::isChannelMaskSpatialized(audio_channel_mask_t channels) {
4843 switch (channels) {
4844 case AUDIO_CHANNEL_OUT_5POINT1:
4845 case AUDIO_CHANNEL_OUT_5POINT1POINT2:
4846 case AUDIO_CHANNEL_OUT_5POINT1POINT4:
4847 case AUDIO_CHANNEL_OUT_7POINT1:
4848 case AUDIO_CHANNEL_OUT_7POINT1POINT2:
4849 case AUDIO_CHANNEL_OUT_7POINT1POINT4:
4850 return true;
4851 default:
4852 return false;
4853 }
4854}
4855
Eric Laurentfa0f6742021-08-17 18:39:44 +02004856bool AudioPolicyManager::canBeSpatialized(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004857 const audio_config_t *config,
4858 const AudioDeviceTypeAddrVector &devices) const
4859{
4860 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
4861 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02004862 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004863 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02004864 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
4865 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
4866 return false;
4867 }
4868 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
4869 return false;
4870 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004871 }
4872
4873 // The caller can have the devices criteria ignored by passing and empty vector, and
Eric Laurentfa0f6742021-08-17 18:39:44 +02004874 // getSpatializerOutputProfile() will ignore the devices when looking for a match.
4875 // Otherwise an output profile supporting a spatializer effect that can be routed
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004876 // to the specified devices must exist.
4877 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02004878 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004879 if (profile == nullptr) {
4880 return false;
4881 }
4882
4883 // The caller can have the audio config criteria ignored by either passing a null ptr or
4884 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02004885 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02004886 // some positional channel masks.
Eric Laurentfa0f6742021-08-17 18:39:44 +02004887 // If the spatializer output is already opened, only channel masks included in the
4888 // spatializer output mixer channel mask are allowed.
Eric Laurent39095982021-08-24 18:29:27 +02004889
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004890 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Eric Laurent39095982021-08-24 18:29:27 +02004891 if (!isChannelMaskSpatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004892 return false;
4893 }
Eric Laurent39095982021-08-24 18:29:27 +02004894 if (mSpatializerOutput != nullptr && mSpatializerOutput->mProfile == profile) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02004895 if ((config->channel_mask & mSpatializerOutput->mMixerChannelMask)
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004896 != config->channel_mask) {
4897 return false;
4898 }
4899 }
4900 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004901 return true;
4902}
4903
4904void AudioPolicyManager::checkVirtualizerClientRoutes() {
4905 std::set<audio_stream_type_t> streamsToInvalidate;
4906 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02004907 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
4908 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004909 audio_attributes_t attr = client->attributes();
4910 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
4911 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
4912 audio_config_base_t clientConfig = client->config();
4913 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02004914 if (desc != mSpatializerOutput
4915 && canBeSpatialized(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004916 streamsToInvalidate.insert(client->stream());
4917 }
4918 }
4919 }
4920
4921 for (audio_stream_type_t stream : streamsToInvalidate) {
4922 mpClientInterface->invalidateStream(stream);
4923 }
4924}
4925
Eric Laurentfa0f6742021-08-17 18:39:44 +02004926status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004927 const audio_attributes_t *attr,
4928 audio_io_handle_t *output) {
4929 *output = AUDIO_IO_HANDLE_NONE;
4930
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004931 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
4932 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
4933 audio_config_t *configPtr = nullptr;
4934 audio_config_t config;
4935 if (mixerConfig != nullptr) {
4936 config = audio_config_initializer(mixerConfig);
4937 configPtr = &config;
4938 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02004939 if (!canBeSpatialized(attr, configPtr, devicesTypeAddress)) {
Eric Laurent39095982021-08-24 18:29:27 +02004940 ALOGW("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004941 return BAD_VALUE;
4942 }
4943
4944 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02004945 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004946 if (profile == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02004947 ALOGW("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004948 return BAD_VALUE;
4949 }
4950
Eric Laurent39095982021-08-24 18:29:27 +02004951 if (mSpatializerOutput != nullptr && mSpatializerOutput->mProfile == profile
4952 && configPtr != nullptr
4953 && configPtr->channel_mask == mSpatializerOutput->mMixerChannelMask) {
4954 *output = mSpatializerOutput->mIoHandle;
4955 ALOGV("%s returns current spatializer output %d", __func__, *output);
4956 return NO_ERROR;
4957 }
4958 mSpatializerOutput.clear();
4959 for (size_t i = 0; i < mOutputs.size(); i++) {
4960 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4961 if (!desc->isDuplicated() && desc->mProfile == profile) {
4962 mSpatializerOutput = desc;
4963 break;
4964 }
4965 }
4966 if (mSpatializerOutput == nullptr) {
4967 ALOGW("%s no opened spatializer output for profile %s",
4968 __func__, profile->getName().c_str());
4969 return BAD_VALUE;
4970 }
4971
4972 if (configPtr != nullptr
4973 && configPtr->channel_mask != mSpatializerOutput->mMixerChannelMask) {
4974 audio_config_base_t savedMixerConfig = {
4975 .sample_rate = mSpatializerOutput->getSamplingRate(),
4976 .format = mSpatializerOutput->getFormat(),
4977 .channel_mask = mSpatializerOutput->mMixerChannelMask,
4978 };
4979 DeviceVector savedDevices = mSpatializerOutput->devices();
4980
4981 closeOutput(mSpatializerOutput->mIoHandle);
4982 mSpatializerOutput.clear();
4983
4984 const sp<SwAudioOutputDescriptor> desc =
4985 new SwAudioOutputDescriptor(profile, mpClientInterface);
4986 status_t status = desc->open(nullptr, mixerConfig, devices,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004987 mEngine->getStreamTypeForAttributes(*attr),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02004988 AUDIO_OUTPUT_FLAG_SPATIALIZER, output);
Eric Laurent39095982021-08-24 18:29:27 +02004989 if (status != NO_ERROR) {
4990 ALOGW("%s failed opening output: status %d, output %d", __func__, status, *output);
4991 if (*output != AUDIO_IO_HANDLE_NONE) {
4992 desc->close();
4993 }
4994 // re open the spatializer output with previous channel mask
4995 status_t newStatus = desc->open(nullptr, &savedMixerConfig, savedDevices,
4996 mEngine->getStreamTypeForAttributes(*attr),
4997 AUDIO_OUTPUT_FLAG_SPATIALIZER, output);
4998 if (newStatus != NO_ERROR) {
4999 if (*output != AUDIO_IO_HANDLE_NONE) {
5000 desc->close();
5001 }
5002 ALOGE("%s failed to re-open mSpatializerOutput, status %d", __func__, newStatus);
5003 } else {
5004 mSpatializerOutput = desc;
5005 addOutput(*output, desc);
5006 }
5007 mPreviousOutputs = mOutputs;
5008 mpClientInterface->onAudioPortListUpdate();
5009 *output = AUDIO_IO_HANDLE_NONE;
5010 return status;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005011 }
Eric Laurent39095982021-08-24 18:29:27 +02005012 mSpatializerOutput = desc;
5013 addOutput(*output, desc);
5014 mPreviousOutputs = mOutputs;
5015 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005016 }
5017
5018 checkVirtualizerClientRoutes();
5019
Eric Laurent39095982021-08-24 18:29:27 +02005020 *output = mSpatializerOutput->mIoHandle;
Eric Laurentfa0f6742021-08-17 18:39:44 +02005021 ALOGV("%s returns new spatializer output %d", __func__, *output);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005022 return NO_ERROR;
5023}
5024
Eric Laurentfa0f6742021-08-17 18:39:44 +02005025status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5026 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005027 return INVALID_OPERATION;
5028 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005029 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005030 return BAD_VALUE;
5031 }
Eric Laurent39095982021-08-24 18:29:27 +02005032
Eric Laurentfa0f6742021-08-17 18:39:44 +02005033 mSpatializerOutput.clear();
Eric Laurent39095982021-08-24 18:29:27 +02005034
5035 checkVirtualizerClientRoutes();
5036
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005037 return NO_ERROR;
5038}
5039
Eric Laurente552edb2014-03-10 17:42:56 -07005040// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005041// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005042// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005043uint32_t AudioPolicyManager::nextAudioPortGeneration()
5044{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005045 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005046}
5047
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005048static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005049 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5050 !audioPolicyXmlConfigFile.empty()) {
5051 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5052 if (ret == NO_ERROR) {
5053 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005054 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005055 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005056 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005057 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005058}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005059
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005060AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5061 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005062 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005063 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005064 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005065 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005066 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005067 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005068 mAudioPortGeneration(1),
5069 mBeaconMuteRefCount(0),
5070 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005071 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005072 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005073 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005074 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005075{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005076}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005077
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005078AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5079 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5080{
5081 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005082}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005083
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005084void AudioPolicyManager::loadConfig() {
5085 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005086 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005087 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005088 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005089 //TODO: b/193496180 use spatializer flag at audio HAL when available
5090 getConfig().convertSpatializerFlag();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005091}
5092
5093status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005094 {
5095 auto engLib = EngineLibrary::load(
5096 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5097 if (!engLib) {
5098 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5099 return NO_INIT;
5100 }
5101 mEngine = engLib->createEngine();
5102 if (mEngine == nullptr) {
5103 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5104 return NO_INIT;
5105 }
François Gaffie2110e042015-03-24 08:41:51 +01005106 }
5107 mEngine->setObserver(this);
5108 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005109 if (status != NO_ERROR) {
5110 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5111 return status;
5112 }
François Gaffie2110e042015-03-24 08:41:51 +01005113
Eric Laurent1d69c872021-01-11 18:53:01 +01005114 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5115 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5116
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005117 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005118 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005119 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005120
Eric Laurent3a4311c2014-03-17 12:00:47 -07005121 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005122 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5123 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5124 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005125 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005126 }
jiabin9ff780e2018-03-19 18:19:52 -07005127 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005128 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005129 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005130 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005131 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005132 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005133 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005134 }
5135 }
5136 }
Eric Laurente552edb2014-03-10 17:42:56 -07005137
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005138 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005139
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005140 // Silence ALOGV statements
5141 property_set("log.tag." LOG_TAG, "D");
5142
Eric Laurente552edb2014-03-10 17:42:56 -07005143 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005144 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005145}
5146
Eric Laurente0720872014-03-11 09:30:41 -07005147AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005148{
Eric Laurente552edb2014-03-10 17:42:56 -07005149 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005150 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005151 }
5152 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005153 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005154 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005155 mAvailableOutputDevices.clear();
5156 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005157 mOutputs.clear();
5158 mInputs.clear();
5159 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005160 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005161 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005162}
5163
Eric Laurente0720872014-03-11 09:30:41 -07005164status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005165{
Eric Laurent87ffa392015-05-22 10:32:38 -07005166 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005167}
5168
Eric Laurente552edb2014-03-10 17:42:56 -07005169// ---
5170
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005171void AudioPolicyManager::onNewAudioModulesAvailable()
5172{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005173 DeviceVector newDevices;
5174 onNewAudioModulesAvailableInt(&newDevices);
5175 if (!newDevices.empty()) {
5176 nextAudioPortGeneration();
5177 mpClientInterface->onAudioPortListUpdate();
5178 }
5179}
5180
5181void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5182{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005183 for (const auto& hwModule : mHwModulesAll) {
5184 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5185 continue;
5186 }
5187 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5188 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5189 ALOGW("could not open HW module %s", hwModule->getName());
5190 continue;
5191 }
5192 mHwModules.push_back(hwModule);
5193 // open all output streams needed to access attached devices
5194 // except for direct output streams that are only opened when they are actually
5195 // required by an app.
5196 // This also validates mAvailableOutputDevices list
5197 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5198 if (!outProfile->canOpenNewIo()) {
5199 ALOGE("Invalid Output profile max open count %u for profile %s",
5200 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5201 continue;
5202 }
5203 if (!outProfile->hasSupportedDevices()) {
5204 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5205 continue;
5206 }
5207 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
5208 mTtsOutputAvailable = true;
5209 }
5210
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005211 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5212 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5213 sp<DeviceDescriptor> supportedDevice = 0;
5214 if (supportedDevices.contains(mDefaultOutputDevice)) {
5215 supportedDevice = mDefaultOutputDevice;
5216 } else {
5217 // choose first device present in profile's SupportedDevices also part of
5218 // mAvailableOutputDevices.
5219 if (availProfileDevices.isEmpty()) {
5220 continue;
5221 }
5222 supportedDevice = availProfileDevices.itemAt(0);
5223 }
5224 if (!mOutputDevicesAll.contains(supportedDevice)) {
5225 continue;
5226 }
5227 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5228 mpClientInterface);
5229 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005230 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5231 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005232 AUDIO_STREAM_DEFAULT,
5233 AUDIO_OUTPUT_FLAG_NONE, &output);
5234 if (status != NO_ERROR) {
5235 ALOGW("Cannot open output stream for devices %s on hw module %s",
5236 supportedDevice->toString().c_str(), hwModule->getName());
5237 continue;
5238 }
5239 for (const auto &device : availProfileDevices) {
5240 // give a valid ID to an attached device once confirmed it is reachable
5241 if (!device->isAttached()) {
5242 device->attach(hwModule);
5243 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005244 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005245 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005246 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5247 }
5248 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005249 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005250 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5251 mPrimaryOutput = outputDesc;
5252 }
Eric Laurent39095982021-08-24 18:29:27 +02005253 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005254 outputDesc->close();
5255 } else {
5256 addOutput(output, outputDesc);
5257 setOutputDevices(outputDesc,
5258 DeviceVector(supportedDevice),
5259 true,
5260 0,
5261 NULL);
5262 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005263 }
5264 // open input streams needed to access attached devices to validate
5265 // mAvailableInputDevices list
5266 for (const auto& inProfile : hwModule->getInputProfiles()) {
5267 if (!inProfile->canOpenNewIo()) {
5268 ALOGE("Invalid Input profile max open count %u for profile %s",
5269 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5270 continue;
5271 }
5272 if (!inProfile->hasSupportedDevices()) {
5273 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5274 continue;
5275 }
5276 // chose first device present in profile's SupportedDevices also part of
5277 // available input devices
5278 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5279 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5280 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005281 ALOGV("%s: Input device list is empty! for profile %s",
5282 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005283 continue;
5284 }
5285 sp<AudioInputDescriptor> inputDesc =
5286 new AudioInputDescriptor(inProfile, mpClientInterface);
5287
5288 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5289 status_t status = inputDesc->open(nullptr,
5290 availProfileDevices.itemAt(0),
5291 AUDIO_SOURCE_MIC,
5292 AUDIO_INPUT_FLAG_NONE,
5293 &input);
5294 if (status != NO_ERROR) {
5295 ALOGW("Cannot open input stream for device %s on hw module %s",
5296 availProfileDevices.toString().c_str(),
5297 hwModule->getName());
5298 continue;
5299 }
5300 for (const auto &device : availProfileDevices) {
5301 // give a valid ID to an attached device once confirmed it is reachable
5302 if (!device->isAttached()) {
5303 device->attach(hwModule);
5304 device->importAudioPortAndPickAudioProfile(inProfile, true);
5305 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005306 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005307 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5308 }
5309 }
5310 inputDesc->close();
5311 }
5312 }
5313}
5314
Eric Laurent98e38192018-02-15 18:31:53 -08005315void AudioPolicyManager::addOutput(audio_io_handle_t output,
5316 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005317{
Eric Laurent1c333e22014-05-20 10:48:17 -07005318 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005319 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005320 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005321 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005322 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005323}
5324
François Gaffie53615e22015-03-19 09:24:12 +01005325void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5326{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005327 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5328 ALOGV("%s: removing primary output", __func__);
5329 mPrimaryOutput = nullptr;
5330 }
François Gaffie53615e22015-03-19 09:24:12 +01005331 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005332 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005333}
5334
Eric Laurent98e38192018-02-15 18:31:53 -08005335void AudioPolicyManager::addInput(audio_io_handle_t input,
5336 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005337{
Eric Laurent1c333e22014-05-20 10:48:17 -07005338 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005339 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005340}
Eric Laurente552edb2014-03-10 17:42:56 -07005341
François Gaffie11d30102018-11-02 16:09:09 +01005342status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005343 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005344 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005345{
François Gaffie11d30102018-11-02 16:09:09 +01005346 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005347 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005348 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005349
François Gaffie11d30102018-11-02 16:09:09 +01005350 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005351 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005352 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005353 }
Eric Laurente552edb2014-03-10 17:42:56 -07005354
Eric Laurent3b73df72014-03-11 09:06:29 -07005355 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005356 // first call getAudioPort to get the supported attributes from the HAL
5357 struct audio_port_v7 port = {};
5358 device->toAudioPort(&port);
5359 status_t status = mpClientInterface->getAudioPort(&port);
5360 if (status == NO_ERROR) {
5361 device->importAudioPort(port);
5362 }
5363
5364 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005365 for (size_t i = 0; i < mOutputs.size(); i++) {
5366 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005367 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005368 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005369 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5370 mOutputs.keyAt(i), device->toString().c_str());
5371 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005372 }
5373 }
5374 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005375 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005376 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005377 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5378 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005379 if (profile->supportsDevice(device)) {
5380 profiles.add(profile);
5381 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5382 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005383 }
5384 }
5385 }
5386
Eric Laurent7b279bb2015-12-14 10:18:23 -08005387 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005388
Eric Laurente552edb2014-03-10 17:42:56 -07005389 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005390 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005391 return BAD_VALUE;
5392 }
5393
5394 // open outputs for matching profiles if needed. Direct outputs are also opened to
5395 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5396 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005397 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005398
5399 // nothing to do if one output is already opened for this profile
5400 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005401 for (j = 0; j < outputs.size(); j++) {
5402 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005403 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005404 // matching profile: save the sample rates, format and channel masks supported
5405 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005406 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005407 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005408 }
Eric Laurente552edb2014-03-10 17:42:56 -07005409 break;
5410 }
5411 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005412 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005413 continue;
5414 }
5415
Eric Laurent3974e3b2017-12-07 17:58:43 -08005416 if (!profile->canOpenNewIo()) {
5417 ALOGW("Max Output number %u already opened for this profile %s",
5418 profile->maxOpenCount, profile->getTagName().c_str());
5419 continue;
5420 }
5421
Eric Laurent83efe1c2017-07-09 16:51:08 -07005422 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005423 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005424 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5425 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005426 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005427 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005428 profiles.removeAt(profile_index);
5429 profile_index--;
5430 } else {
5431 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005432 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005433 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005434 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5435 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005436 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005437 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005438
François Gaffie11d30102018-11-02 16:09:09 +01005439 if (device_distinguishes_on_address(deviceType)) {
5440 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5441 device->toString().c_str());
5442 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5443 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005444 }
Eric Laurente552edb2014-03-10 17:42:56 -07005445 ALOGV("checkOutputsForDevice(): adding output %d", output);
5446 }
5447 }
5448
5449 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005450 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005451 return BAD_VALUE;
5452 }
Eric Laurentd4692962014-05-05 18:13:44 -07005453 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005454 // check if one opened output is not needed any more after disconnecting one device
5455 for (size_t i = 0; i < mOutputs.size(); i++) {
5456 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005457 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005458 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005459 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffied7a5f2d2021-10-20 17:07:13 +02005460 && desc->containsSingleDeviceSupportingEncodedFormats(device)
5461 && !mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
François Gaffie11d30102018-11-02 16:09:09 +01005462 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005463 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005464 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5465 mOutputs.keyAt(i));
5466 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005467 }
Eric Laurente552edb2014-03-10 17:42:56 -07005468 }
5469 }
Eric Laurentd4692962014-05-05 18:13:44 -07005470 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005471 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005472 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5473 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005474 if (!profile->supportsDevice(device)) {
5475 continue;
5476 }
5477 ALOGV("checkOutputsForDevice(): "
5478 "clearing direct output profile %zu on module %s",
5479 j, hwModule->getName());
5480 profile->clearAudioProfiles();
5481 if (!profile->hasDynamicAudioProfile()) {
5482 continue;
5483 }
5484 // When a device is disconnected, if there is an IOProfile that contains dynamic
5485 // profiles and supports the disconnected device, call getAudioPort to repopulate
5486 // the capabilities of the devices that is supported by the IOProfile.
5487 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5488 if (supportedDevice == device ||
5489 !mAvailableOutputDevices.contains(supportedDevice)) {
5490 continue;
5491 }
5492 struct audio_port_v7 port;
5493 supportedDevice->toAudioPort(&port);
5494 status_t status = mpClientInterface->getAudioPort(&port);
5495 if (status == NO_ERROR) {
5496 supportedDevice->importAudioPort(port);
5497 }
Eric Laurente552edb2014-03-10 17:42:56 -07005498 }
5499 }
5500 }
5501 }
5502 return NO_ERROR;
5503}
5504
François Gaffie11d30102018-11-02 16:09:09 +01005505status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005506 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005507{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005508 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005509
François Gaffie11d30102018-11-02 16:09:09 +01005510 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005511 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005512 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005513 }
5514
Eric Laurentd4692962014-05-05 18:13:44 -07005515 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005516 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005517 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005518 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005519 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005520 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005521 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005522 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005523
François Gaffie11d30102018-11-02 16:09:09 +01005524 if (profile->supportsDevice(device)) {
5525 profiles.add(profile);
5526 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5527 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005528 }
5529 }
5530 }
5531
Eric Laurent0dd51852019-04-19 18:18:58 -07005532 if (profiles.isEmpty()) {
5533 ALOGW("%s: No input profile available for device %s",
5534 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005535 return BAD_VALUE;
5536 }
5537
5538 // open inputs for matching profiles if needed. Direct inputs are also opened to
5539 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5540 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5541
Eric Laurent1c333e22014-05-20 10:48:17 -07005542 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005543
Eric Laurentd4692962014-05-05 18:13:44 -07005544 // nothing to do if one input is already opened for this profile
5545 size_t input_index;
5546 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5547 desc = mInputs.valueAt(input_index);
5548 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005549 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005550 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005551 }
Eric Laurentd4692962014-05-05 18:13:44 -07005552 break;
5553 }
5554 }
5555 if (input_index != mInputs.size()) {
5556 continue;
5557 }
5558
Eric Laurent3974e3b2017-12-07 17:58:43 -08005559 if (!profile->canOpenNewIo()) {
5560 ALOGW("Max Input number %u already opened for this profile %s",
5561 profile->maxOpenCount, profile->getTagName().c_str());
5562 continue;
5563 }
5564
Eric Laurentfe231122017-11-17 17:48:06 -08005565 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005566 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005567 status_t status = desc->open(nullptr,
5568 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005569 AUDIO_SOURCE_MIC,
5570 AUDIO_INPUT_FLAG_NONE,
5571 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005572
Eric Laurentcf2c0212014-07-25 16:20:43 -07005573 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005574 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005575 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005576 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005577 mpClientInterface->setParameters(input, String8(param));
5578 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005579 }
François Gaffie11d30102018-11-02 16:09:09 +01005580 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005581 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005582 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005583 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005584 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005585 }
5586
Eric Laurent0dd51852019-04-19 18:18:58 -07005587 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005588 addInput(input, desc);
5589 }
5590 } // endif input != 0
5591
Eric Laurentcf2c0212014-07-25 16:20:43 -07005592 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005593 ALOGW("%s could not open input for device %s", __func__,
5594 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005595 profiles.removeAt(profile_index);
5596 profile_index--;
5597 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005598 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005599 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005600 }
Eric Laurentd4692962014-05-05 18:13:44 -07005601 ALOGV("checkInputsForDevice(): adding input %d", input);
5602 }
5603 } // end scan profiles
5604
5605 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005606 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005607 return BAD_VALUE;
5608 }
5609 } else {
5610 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005611 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005612 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005613 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005614 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005615 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005616 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005617 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005618 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5619 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005620 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005621 }
5622 }
5623 }
5624 } // end disconnect
5625
5626 return NO_ERROR;
5627}
5628
5629
Eric Laurente0720872014-03-11 09:30:41 -07005630void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005631{
5632 ALOGV("closeOutput(%d)", output);
5633
François Gaffie1c878552018-11-22 16:53:21 +01005634 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5635 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005636 ALOGW("closeOutput() unknown output %d", output);
5637 return;
5638 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005639 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005640 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005641
Eric Laurente552edb2014-03-10 17:42:56 -07005642 // look for duplicated outputs connected to the output being removed.
5643 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005644 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5645 if (dupOutput->isDuplicated() &&
5646 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5647 sp<SwAudioOutputDescriptor> remainingOutput =
5648 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005649 // As all active tracks on duplicated output will be deleted,
5650 // and as they were also referenced on the other output, the reference
5651 // count for their stream type must be adjusted accordingly on
5652 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005653 const bool wasActive = remainingOutput->isActive();
5654 // Note: no-op on the closing output where all clients has already been set inactive
5655 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005656 // stop() will be a no op if the output is still active but is needed in case all
5657 // active streams refcounts where cleared above
5658 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005659 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005660 }
Eric Laurente552edb2014-03-10 17:42:56 -07005661 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5662 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5663
5664 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005665 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005666 }
5667 }
5668
Eric Laurent05b90f82014-08-27 15:32:29 -07005669 nextAudioPortGeneration();
5670
François Gaffie1c878552018-11-22 16:53:21 +01005671 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005672 if (index >= 0) {
5673 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005674 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5675 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005676 mAudioPatches.removeItemsAt(index);
5677 mpClientInterface->onAudioPatchListUpdate();
5678 }
5679
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005680 if (closingOutputWasActive) {
5681 closingOutput->stop();
5682 }
François Gaffie1c878552018-11-22 16:53:21 +01005683 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005684
François Gaffie53615e22015-03-19 09:24:12 +01005685 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005686 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005687
5688 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5689 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005690 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005691 bool directOutputOpen = false;
5692 for (size_t i = 0; i < mOutputs.size(); i++) {
5693 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5694 directOutputOpen = true;
5695 break;
5696 }
5697 }
5698 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11005699 ALOGV("no direct outputs open, reset MSD patches");
5700 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5701 // how output devices for patching are resolved. Avoid by caching and reusing the
5702 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5703 // devices to patch to. This may be complicated by the fact that devices may become
5704 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005705 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005706 }
5707 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005708}
5709
5710void AudioPolicyManager::closeInput(audio_io_handle_t input)
5711{
5712 ALOGV("closeInput(%d)", input);
5713
5714 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5715 if (inputDesc == NULL) {
5716 ALOGW("closeInput() unknown input %d", input);
5717 return;
5718 }
5719
Eric Laurent6a94d692014-05-20 11:18:06 -07005720 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005721
François Gaffie11d30102018-11-02 16:09:09 +01005722 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005723 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005724 if (index >= 0) {
5725 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005726 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5727 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005728 mAudioPatches.removeItemsAt(index);
5729 mpClientInterface->onAudioPatchListUpdate();
5730 }
5731
Eric Laurentfe231122017-11-17 17:48:06 -08005732 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005733 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005734
François Gaffie11d30102018-11-02 16:09:09 +01005735 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5736 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005737 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005738 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005739 }
Eric Laurente552edb2014-03-10 17:42:56 -07005740}
5741
François Gaffie11d30102018-11-02 16:09:09 +01005742SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5743 const DeviceVector &devices,
5744 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005745{
5746 SortedVector<audio_io_handle_t> outputs;
5747
François Gaffie11d30102018-11-02 16:09:09 +01005748 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005749 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005750 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005751 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005752 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005753 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005754 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005755 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005756 outputs.add(openOutputs.keyAt(i));
5757 }
5758 }
5759 return outputs;
5760}
5761
Mikhail Naganov37977152018-07-11 15:54:44 -07005762void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5763{
5764 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5765 // output is suspended before any tracks are moved to it
5766 checkA2dpSuspend();
5767 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005768 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005769 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005770 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005771 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11005772 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
5773 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
5774 // configuration changes will ultimately be rerouted correctly. We can still avoid
5775 // unnecessary rerouting by caching and reusing the arguments to
5776 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
5777 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005778 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005779 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07005780 // an event that changed routing likely occurred, inform upper layers
5781 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07005782}
5783
François Gaffiec005e562018-11-06 15:04:49 +01005784bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5785 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005786{
François Gaffiec005e562018-11-06 15:04:49 +01005787 return mEngine->getProductStrategyForAttributes(lAttr) ==
5788 mEngine->getProductStrategyForAttributes(rAttr);
5789}
5790
Francois Gaffieff1eb522020-05-06 18:37:04 +02005791void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
5792{
5793 for (size_t i = 0; i < mAudioSources.size(); i++) {
5794 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5795 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005796 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
5797 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02005798 connectAudioSource(sourceDesc);
5799 }
5800 }
5801}
5802
5803void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
5804{
5805 for (size_t i = 0; i < mAudioSources.size(); i++) {
5806 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5807 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
5808 && sourceDesc->swOutput().promote()->mIoHandle == output) {
5809 disconnectAudioSource(sourceDesc);
5810 }
5811 }
5812}
5813
François Gaffiec005e562018-11-06 15:04:49 +01005814void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5815{
5816 auto psId = mEngine->getProductStrategyForAttributes(attr);
5817
5818 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5819 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005820
François Gaffie11d30102018-11-02 16:09:09 +01005821 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5822 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005823
Eric Laurentc209fe42020-06-05 18:11:23 -07005824 uint32_t maxLatency = 0;
5825 bool invalidate = false;
5826 // take into account dynamic audio policies related changes: if a client is now associated
5827 // to a different policy mix than at creation time, invalidate corresponding stream
5828 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5829 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5830 if (desc->isDuplicated()) {
5831 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005832 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005833 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5834 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5835 continue;
5836 }
5837 sp<AudioPolicyMix> primaryMix;
5838 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5839 client->flags(), primaryMix, nullptr);
5840 if (status != OK) {
5841 continue;
5842 }
yucliuf4de36d2020-09-14 14:57:56 -07005843 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005844 invalidate = true;
5845 if (desc->isStrategyActive(psId)) {
5846 maxLatency = desc->latency();
5847 }
5848 break;
5849 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005850 }
5851 }
5852
Eric Laurentc209fe42020-06-05 18:11:23 -07005853 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005854 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5855 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005856 for (audio_io_handle_t srcOut : srcOutputs) {
5857 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005858 if (desc == nullptr) continue;
5859
5860 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005861 maxLatency = desc->latency();
5862 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005863
5864 if (invalidate) continue;
5865
5866 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005867 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005868 // a client on a non direct outputs has necessarily a linear PCM format
5869 // so we can call selectOutput() safely
5870 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5871 client->flags(),
5872 client->config().format,
5873 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07005874 client->config().sample_rate,
5875 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07005876 if (newOutput != srcOut) {
5877 invalidate = true;
5878 break;
5879 }
5880 } else {
5881 sp<IOProfile> profile = getProfileForOutput(newDevices,
5882 client->config().sample_rate,
5883 client->config().format,
5884 client->config().channel_mask,
5885 client->flags(),
5886 true /* directOnly */);
5887 if (profile != desc->mProfile) {
5888 invalidate = true;
5889 break;
5890 }
5891 }
5892 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005893 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005894
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005895 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005896 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005897 std::to_string(srcOutputs[0]).c_str(),
5898 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005899 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005900 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005901 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005902 if (desc == nullptr) continue;
5903
5904 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005905 setStrategyMute(psId, true, desc);
5906 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005907 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005908 }
François Gaffiec005e562018-11-06 15:04:49 +01005909 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005910 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005911 connectAudioSource(source);
5912 }
Eric Laurente552edb2014-03-10 17:42:56 -07005913 }
5914
François Gaffiec005e562018-11-06 15:04:49 +01005915 // Move effects associated to this stream from previous output to new output
5916 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005917 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005918 }
François Gaffiec005e562018-11-06 15:04:49 +01005919 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005920 if (invalidate) {
5921 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5922 mpClientInterface->invalidateStream(stream);
5923 }
Eric Laurente552edb2014-03-10 17:42:56 -07005924 }
5925 }
5926}
5927
Eric Laurente0720872014-03-11 09:30:41 -07005928void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005929{
François Gaffiec005e562018-11-06 15:04:49 +01005930 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5931 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5932 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02005933 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01005934 }
Eric Laurente552edb2014-03-10 17:42:56 -07005935}
5936
Kevin Rocard153f92d2018-12-18 18:33:28 -08005937void AudioPolicyManager::checkSecondaryOutputs() {
5938 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00005939 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08005940 for (size_t i = 0; i < mOutputs.size(); i++) {
5941 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5942 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005943 sp<AudioPolicyMix> primaryMix;
5944 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07005945 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07005946 client->flags(), primaryMix, &secondaryMixes);
5947 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5948 for (auto &secondaryMix : secondaryMixes) {
5949 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5950 if (outputDesc != nullptr &&
5951 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5952 secondaryDescs.push_back(outputDesc);
5953 }
5954 }
5955
jiabin10a03f12021-05-07 23:46:28 +00005956 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08005957 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00005958 } else if (!std::equal(
5959 client->getSecondaryOutputs().begin(),
5960 client->getSecondaryOutputs().end(),
5961 secondaryDescs.begin(), secondaryDescs.end())) {
5962 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
5963 std::vector<audio_io_handle_t> secondaryOutputIds;
5964 for (const auto& secondaryDesc : secondaryDescs) {
5965 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
5966 weakSecondaryDescs.push_back(secondaryDesc);
5967 }
5968 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
5969 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
Kevin Rocard153f92d2018-12-18 18:33:28 -08005970 }
5971 }
5972 }
jiabin10a03f12021-05-07 23:46:28 +00005973 if (!trackSecondaryOutputs.empty()) {
5974 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
5975 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08005976 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00005977 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08005978 mpClientInterface->invalidateStream(stream);
5979 }
5980}
5981
Eric Laurent2517af32020-11-25 15:31:27 +01005982bool AudioPolicyManager::isScoRequestedForComm() const {
5983 AudioDeviceTypeAddrVector devices;
5984 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
5985 for (const auto &device : devices) {
5986 if (audio_is_bluetooth_out_sco_device(device.mType)) {
5987 return true;
5988 }
5989 }
5990 return false;
5991}
5992
Eric Laurente0720872014-03-11 09:30:41 -07005993void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005994{
François Gaffie53615e22015-03-19 09:24:12 +01005995 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005996 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005997 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005998 return;
5999 }
6000
Eric Laurent3a4311c2014-03-17 12:00:47 -07006001 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006002 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6003 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006004 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006005
6006 // if suspended, restore A2DP output if:
6007 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006008 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006009 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006010 //
Eric Laurentf732e072016-08-03 19:30:28 -07006011 // if not suspended, suspend A2DP output if:
6012 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006013 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006014 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006015 //
6016 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006017 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006018 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006019 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006020 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006021
6022 mpClientInterface->restoreOutput(a2dpOutput);
6023 mA2dpSuspended = false;
6024 }
6025 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006026 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006027 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006028 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006029 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006030
6031 mpClientInterface->suspendOutput(a2dpOutput);
6032 mA2dpSuspended = true;
6033 }
6034 }
6035}
6036
François Gaffie11d30102018-11-02 16:09:09 +01006037DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6038 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006039{
François Gaffie11d30102018-11-02 16:09:09 +01006040 DeviceVector devices;
6041
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006042 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006043 if (index >= 0) {
6044 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006045 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006046 ALOGV("%s device %s forced by patch %d", __func__,
6047 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6048 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006049 }
6050 }
6051
Dean Wheatley514b4312020-06-17 21:45:00 +10006052 // Do not retrieve engine device for outputs through MSD
6053 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6054 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6055 return outputDesc->devices();
6056 }
6057
Eric Laurent97ac8712018-07-27 18:59:02 -07006058 // Honor explicit routing requests only if no client using default routing is active on this
6059 // input: a specific app can not force routing for other apps by setting a preferred device.
6060 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006061 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006062 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006063 if (device != nullptr) {
6064 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006065 }
6066
François Gaffiea807ef92018-11-05 10:44:33 +01006067 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6068 // of setForceUse / Default Bus device here
6069 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6070 if (device != nullptr) {
6071 return DeviceVector(device);
6072 }
6073
François Gaffiec005e562018-11-06 15:04:49 +01006074 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6075 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6076 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306077 auto hasStreamActive = [&](auto stream) {
6078 return hasStream(streams, stream) && isStreamActive(stream, 0);
6079 };
Eric Laurent484e9272018-06-07 17:29:23 -07006080
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306081 auto doGetOutputDevicesForVoice = [&]() {
6082 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
6083 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL))) &&
6084 (isInCall() ||
6085 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc));
6086 };
6087
6088 // With low-latency playing on speaker, music on WFD, when the first low-latency
6089 // output is stopped, getNewOutputDevices checks for a product strategy
6090 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006091 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306092 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6093 // stream is associated to the output descriptor.
6094 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6095 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6096 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6097 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006098 // Retrieval of devices for voice DL is done on primary output profile, cannot
6099 // check the route (would force modifying configuration file for this profile)
6100 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6101 break;
6102 }
Eric Laurente552edb2014-03-10 17:42:56 -07006103 }
François Gaffiec005e562018-11-06 15:04:49 +01006104 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006105 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006106}
6107
François Gaffie11d30102018-11-02 16:09:09 +01006108sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6109 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006110{
François Gaffie11d30102018-11-02 16:09:09 +01006111 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006112
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006113 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006114 if (index >= 0) {
6115 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006116 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006117 ALOGV("getNewInputDevice() device %s forced by patch %d",
6118 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6119 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006120 }
6121 }
6122
Eric Laurent97ac8712018-07-27 18:59:02 -07006123 // Honor explicit routing requests only if no client using default routing is active on this
6124 // input: a specific app can not force routing for other apps by setting a preferred device.
6125 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006126 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6127 if (device != nullptr) {
6128 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006129 }
6130
Eric Laurentdc95a252018-04-12 12:46:56 -07006131 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006132 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006133 audio_attributes_t attributes;
6134 uid_t uid;
6135 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6136 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006137 attributes = topClient->attributes();
6138 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006139 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006140 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6141 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006142 }
6143
Francois Gaffie716e1432019-01-14 16:58:59 +01006144 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6145 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006146 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006147 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006148 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006149 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006150
Eric Laurente552edb2014-03-10 17:42:56 -07006151 return device;
6152}
6153
Eric Laurent794fde22016-03-11 09:50:45 -08006154bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6155 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006156 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006157}
6158
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006159DeviceTypeSet AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006160 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01006161 // getOutputDevicesForStream's behavior for invalid streams.
6162 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
6163 // device for music stream), but we want to return the empty set.
6164 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006165 return DeviceTypeSet{};
Eric Laurent6a94d692014-05-20 11:18:06 -07006166 }
François Gaffie11d30102018-11-02 16:09:09 +01006167 DeviceVector activeDevices;
6168 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00006169 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
6170 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01006171 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08006172 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07006173 }
François Gaffiec005e562018-11-06 15:04:49 +01006174 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01006175 devices.merge(curDevices);
6176 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006177 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07006178 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01006179 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08006180 }
6181 }
Eric Laurente552edb2014-03-10 17:42:56 -07006182 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006183
Eric Laurentb0688d62018-08-14 15:49:18 -07006184 // Favor devices selected on active streams if any to report correct device in case of
6185 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01006186 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07006187 devices = activeDevices;
6188 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006189 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
6190 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07006191 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01006192 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07006193 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01006194 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05006195 }
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006196 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07006197}
6198
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006199status_t AudioPolicyManager::getDevicesForAttributes(
6200 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
6201 if (devices == nullptr) {
6202 return BAD_VALUE;
6203 }
6204 // check dynamic policies but only for primary descriptors (secondary not used for audible
6205 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006206 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006207 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07006208 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006209 if (status != OK) {
6210 return status;
6211 }
Eric Laurentc529cf62020-04-17 18:19:10 -07006212 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
6213 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
6214 devices->push_back(device);
6215 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006216 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006217 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6218 for (const auto& device : curDevices) {
6219 devices->push_back(device->getDeviceTypeAddr());
6220 }
6221 return NO_ERROR;
6222}
6223
Eric Laurente0720872014-03-11 09:30:41 -07006224void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006225 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006226 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006227 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006228 updateDevicesAndOutputs();
6229 break;
6230 default:
6231 break;
6232 }
6233}
6234
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006235uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006236
6237 // skip beacon mute management if a dedicated TTS output is available
6238 if (mTtsOutputAvailable) {
6239 return 0;
6240 }
6241
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006242 switch(event) {
6243 case STARTING_OUTPUT:
6244 mBeaconMuteRefCount++;
6245 break;
6246 case STOPPING_OUTPUT:
6247 if (mBeaconMuteRefCount > 0) {
6248 mBeaconMuteRefCount--;
6249 }
6250 break;
6251 case STARTING_BEACON:
6252 mBeaconPlayingRefCount++;
6253 break;
6254 case STOPPING_BEACON:
6255 if (mBeaconPlayingRefCount > 0) {
6256 mBeaconPlayingRefCount--;
6257 }
6258 break;
6259 }
6260
6261 if (mBeaconMuteRefCount > 0) {
6262 // any playback causes beacon to be muted
6263 return setBeaconMute(true);
6264 } else {
6265 // no other playback: unmute when beacon starts playing, mute when it stops
6266 return setBeaconMute(mBeaconPlayingRefCount == 0);
6267 }
6268}
6269
6270uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6271 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6272 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6273 // keep track of muted state to avoid repeating mute/unmute operations
6274 if (mBeaconMuted != mute) {
6275 // mute/unmute AUDIO_STREAM_TTS on all outputs
6276 ALOGV("\t muting %d", mute);
6277 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01006278 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006279 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006280 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006281 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006282 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006283 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006284 maxLatency = latency;
6285 }
6286 }
6287 mBeaconMuted = mute;
6288 return maxLatency;
6289 }
6290 return 0;
6291}
6292
Eric Laurente0720872014-03-11 09:30:41 -07006293void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006294{
François Gaffiec005e562018-11-06 15:04:49 +01006295 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006296 mPreviousOutputs = mOutputs;
6297}
6298
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006299uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006300 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006301 uint32_t delayMs)
6302{
6303 // mute/unmute strategies using an incompatible device combination
6304 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6305 // if unmuting, unmute only after the specified delay
6306 if (outputDesc->isDuplicated()) {
6307 return 0;
6308 }
6309
6310 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006311 DeviceVector devices = outputDesc->devices();
6312 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006313
François Gaffiec005e562018-11-06 15:04:49 +01006314 auto productStrategies = mEngine->getOrderedProductStrategies();
6315 for (const auto &productStrategy : productStrategies) {
6316 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6317 DeviceVector curDevices =
6318 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6319 curDevices = curDevices.filter(outputDesc->supportedDevices());
6320 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006321 bool doMute = false;
6322
François Gaffiec005e562018-11-06 15:04:49 +01006323 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006324 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006325 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6326 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006327 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006328 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006329 }
Eric Laurent99401132014-05-07 19:48:15 -07006330 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006331 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006332 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006333 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006334 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006335 continue;
6336 }
François Gaffiec005e562018-11-06 15:04:49 +01006337 ALOGVV("%s() %s (curDevice %s)", __func__,
6338 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6339 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6340 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006341 if (mute) {
6342 // FIXME: should not need to double latency if volume could be applied
6343 // immediately by the audioflinger mixer. We must account for the delay
6344 // between now and the next time the audioflinger thread for this output
6345 // will process a buffer (which corresponds to one buffer size,
6346 // usually 1/2 or 1/4 of the latency).
6347 if (muteWaitMs < desc->latency() * 2) {
6348 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006349 }
6350 }
6351 }
6352 }
6353 }
6354 }
6355
Eric Laurent99401132014-05-07 19:48:15 -07006356 // temporary mute output if device selection changes to avoid volume bursts due to
6357 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006358 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006359 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006360
Eric Laurentdc462862016-07-19 12:29:53 -07006361 if (muteWaitMs < tempMuteWaitMs) {
6362 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006363 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006364
6365 // If recommended duration is defined, replace temporary mute duration to avoid
6366 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6367 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6368 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6369 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6370 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6371
François Gaffieaaac0fd2018-11-22 17:56:39 +01006372 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6373 // make sure that we do not start the temporary mute period too early in case of
6374 // delayed device change
6375 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6376 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006377 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006378 }
6379 }
6380
Eric Laurente552edb2014-03-10 17:42:56 -07006381 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6382 if (muteWaitMs > delayMs) {
6383 muteWaitMs -= delayMs;
6384 usleep(muteWaitMs * 1000);
6385 return muteWaitMs;
6386 }
6387 return 0;
6388}
6389
François Gaffie11d30102018-11-02 16:09:09 +01006390uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6391 const DeviceVector &devices,
6392 bool force,
6393 int delayMs,
6394 audio_patch_handle_t *patchHandle,
6395 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006396{
François Gaffie11d30102018-11-02 16:09:09 +01006397 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006398 uint32_t muteWaitMs;
6399
6400 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006401 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6402 nullptr /* patchHandle */, requiresMuteCheck);
6403 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6404 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006405 return muteWaitMs;
6406 }
Eric Laurente552edb2014-03-10 17:42:56 -07006407
6408 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006409 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006410 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07006411
François Gaffie11d30102018-11-02 16:09:09 +01006412 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6413
6414 if (!filteredDevices.isEmpty()) {
6415 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006416 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006417
6418 // if the outputs are not materially active, there is no need to mute.
6419 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006420 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006421 } else {
6422 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6423 muteWaitMs = 0;
6424 }
Eric Laurente552edb2014-03-10 17:42:56 -07006425
Eric Laurent79ea9582020-06-11 18:49:24 -07006426 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6427 // output profile or if new device is not supported AND previous device(s) is(are) still
6428 // available (otherwise reset device must be done on the output)
6429 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
6430 !mAvailableOutputDevices.filter(prevDevices).empty()) {
6431 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6432 // restore previous device after evaluating strategy mute state
6433 outputDesc->setDevices(prevDevices);
6434 return muteWaitMs;
6435 }
6436
Eric Laurente552edb2014-03-10 17:42:56 -07006437 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006438 // the requested device is AUDIO_DEVICE_NONE
6439 // OR the requested device is the same as current device
6440 // AND force is not specified
6441 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006442 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006443 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01006444 !force && outputDesc->getPatchHandle() != 0) {
6445 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6446 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07006447 return muteWaitMs;
6448 }
6449
François Gaffie11d30102018-11-02 16:09:09 +01006450 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006451
Eric Laurente552edb2014-03-10 17:42:56 -07006452 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01006453 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006454 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006455 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006456 PatchBuilder patchBuilder;
6457 patchBuilder.addSource(outputDesc);
6458 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6459 for (const auto &filteredDevice : filteredDevices) {
6460 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006461 }
6462
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006463 // Add half reported latency to delayMs when muteWaitMs is null in order
6464 // to avoid disordered sequence of muting volume and changing devices.
6465 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6466 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006467 }
Eric Laurente552edb2014-03-10 17:42:56 -07006468
6469 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006470 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006471
6472 return muteWaitMs;
6473}
6474
Eric Laurentc75307b2015-03-17 15:29:32 -07006475status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006476 int delayMs,
6477 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006478{
Eric Laurent6a94d692014-05-20 11:18:06 -07006479 ssize_t index;
6480 if (patchHandle) {
6481 index = mAudioPatches.indexOfKey(*patchHandle);
6482 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006483 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006484 }
6485 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006486 return INVALID_OPERATION;
6487 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006488 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006489 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006490 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006491 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006492 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006493 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006494 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006495 return status;
6496}
6497
6498status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006499 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006500 bool force,
6501 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006502{
6503 status_t status = NO_ERROR;
6504
Eric Laurent1f2f2232014-06-02 12:01:23 -07006505 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006506 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6507 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006508
François Gaffie11d30102018-11-02 16:09:09 +01006509 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006510 PatchBuilder patchBuilder;
6511 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006512 // AUDIO_SOURCE_HOTWORD is for internal use only:
6513 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006514 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6515 auto result = usecase;
6516 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6517 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6518 }
6519 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006520 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006521 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006522 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006523 }
6524 }
6525 return status;
6526}
6527
Eric Laurent6a94d692014-05-20 11:18:06 -07006528status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6529 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006530{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006531 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006532 ssize_t index;
6533 if (patchHandle) {
6534 index = mAudioPatches.indexOfKey(*patchHandle);
6535 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006536 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006537 }
6538 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006539 return INVALID_OPERATION;
6540 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006541 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006542 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006543 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006544 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006545 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006546 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006547 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006548 return status;
6549}
6550
François Gaffie11d30102018-11-02 16:09:09 +01006551sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006552 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006553 audio_format_t& format,
6554 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006555 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006556{
6557 // Choose an input profile based on the requested capture parameters: select the first available
6558 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006559 //
6560 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6561 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006562
Glenn Kasten730b9262018-03-29 15:01:26 -07006563 sp<IOProfile> firstInexact;
6564 uint32_t updatedSamplingRate = 0;
6565 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6566 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006567 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006568 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006569 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006570 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006571 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006572 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006573 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006574 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006575 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006576 &channelMask /*updatedChannelMask*/,
6577 // FIXME ugly cast
6578 (audio_output_flags_t) flags,
6579 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006580 return profile;
6581 }
François Gaffie11d30102018-11-02 16:09:09 +01006582 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006583 samplingRate,
6584 &updatedSamplingRate,
6585 format,
6586 &updatedFormat,
6587 channelMask,
6588 &updatedChannelMask,
6589 // FIXME ugly cast
6590 (audio_output_flags_t) flags,
6591 false /*exactMatchRequiredForInputFlags*/)) {
6592 firstInexact = profile;
6593 }
6594
Eric Laurente552edb2014-03-10 17:42:56 -07006595 }
6596 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006597 if (firstInexact != nullptr) {
6598 samplingRate = updatedSamplingRate;
6599 format = updatedFormat;
6600 channelMask = updatedChannelMask;
6601 return firstInexact;
6602 }
Eric Laurente552edb2014-03-10 17:42:56 -07006603 return NULL;
6604}
6605
François Gaffieaaac0fd2018-11-22 17:56:39 +01006606float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6607 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006608 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006609 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006610{
jiabin9a3361e2019-10-01 09:38:30 -07006611 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006612
6613 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6614 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6615 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6616 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006617 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6618 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6619 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6620 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006621 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006622
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006623 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006624 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6625 mOutputs.isActive(ringVolumeSrc, 0)) {
6626 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006627 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006628 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006629 }
6630
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006631 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006632 if ((volumeSource != callVolumeSrc && (isInCall() ||
6633 mOutputs.isActiveLocally(callVolumeSrc))) &&
6634 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6635 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6636 volumeSource == alarmVolumeSrc ||
6637 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6638 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6639 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006640 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006641 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006642 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006643 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006644 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006645 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006646 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6647 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6648 // programmatically muted.
6649 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6650 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6651 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006652 bool exemptFromCapping =
6653 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6654 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006655 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6656 volumeSource, volumeDb);
6657 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006658 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6659 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6660 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006661 }
6662 }
Eric Laurente552edb2014-03-10 17:42:56 -07006663 // if a headset is connected, apply the following rules to ring tones and notifications
6664 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006665 // - always attenuate notifications volume by 6dB
6666 // - attenuate ring tones volume by 6dB unless music is not playing and
6667 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006668 // - if music is playing, always limit the volume to current music volume,
6669 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006670 if (!Intersection(deviceTypes,
6671 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6672 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006673 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6674 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006675 ((volumeSource == alarmVolumeSrc ||
6676 volumeSource == ringVolumeSrc) ||
6677 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6678 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6679 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6680 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6681 curves.canBeMuted()) {
6682
Eric Laurente552edb2014-03-10 17:42:56 -07006683 // when the phone is ringing we must consider that music could have been paused just before
6684 // by the music application and behave as if music was active if the last music track was
6685 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006686 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006687 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006688 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006689 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006690 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6691 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006692 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006693 float musicVolDb = computeVolume(musicCurves,
6694 musicVolumeSrc,
6695 musicCurves.getVolumeIndex(musicDevice),
6696 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006697 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6698 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6699 if (volumeDb > minVolDb) {
6700 volumeDb = minVolDb;
6701 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006702 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02006703 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
6704 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6705 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006706 // on A2DP, also ensure notification volume is not too low compared to media when
6707 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006708 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006709 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006710 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6711 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006712 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6713 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006714 }
6715 }
jiabin9a3361e2019-10-01 09:38:30 -07006716 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006717 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006718 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006719 }
6720 }
6721
François Gaffie43c73442018-11-08 08:21:55 +01006722 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006723}
6724
Eric Laurent3839bc02018-07-10 18:33:34 -07006725int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006726 VolumeSource fromVolumeSource,
6727 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006728{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006729 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006730 return srcIndex;
6731 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006732 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6733 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006734 float minSrc = (float)srcCurves.getVolumeIndexMin();
6735 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6736 float minDst = (float)dstCurves.getVolumeIndexMin();
6737 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006738
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006739 // preserve mute request or correct range
6740 if (srcIndex < minSrc) {
6741 if (srcIndex == 0) {
6742 return 0;
6743 }
6744 srcIndex = minSrc;
6745 } else if (srcIndex > maxSrc) {
6746 srcIndex = maxSrc;
6747 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006748 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6749}
6750
François Gaffieaaac0fd2018-11-22 17:56:39 +01006751status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6752 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006753 int index,
6754 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006755 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006756 int delayMs,
6757 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006758{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006759 // do not change actual attributes volume if the attributes is muted
6760 if (outputDesc->isMuted(volumeSource)) {
6761 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6762 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006763 return NO_ERROR;
6764 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006765 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6766 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
6767 bool isVoiceVolSrc = callVolSrc == volumeSource;
6768 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
6769
Eric Laurent2517af32020-11-25 15:31:27 +01006770 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006771 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006772 // if sco and call follow same curves, bypass forceUseForComm
6773 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006774 ((isVoiceVolSrc && isScoRequested) ||
6775 (isBtScoVolSrc && !isScoRequested))) {
6776 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6777 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07006778 // Do not return an error here as AudioService will always set both voice call
6779 // and bluetooth SCO volumes due to stream aliasing.
6780 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006781 }
jiabin9a3361e2019-10-01 09:38:30 -07006782 if (deviceTypes.empty()) {
6783 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006784 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006785
jiabin9a3361e2019-10-01 09:38:30 -07006786 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6787 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07006788 // Force VoIP volume to max for bluetooth SCO device except if muted
6789 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07006790 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006791 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006792 }
jiabin9a3361e2019-10-01 09:38:30 -07006793 outputDesc->setVolume(
6794 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006795
Eric Laurente8f2c0f2021-08-17 11:17:19 +02006796 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006797 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006798 // 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 +01006799 if (isVoiceVolSrc) {
6800 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006801 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006802 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006803 }
Eric Laurent18fba842016-03-31 14:41:26 -07006804 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006805 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6806 mLastVoiceVolume = voiceVolume;
6807 }
6808 }
Eric Laurente552edb2014-03-10 17:42:56 -07006809 return NO_ERROR;
6810}
6811
Eric Laurentc75307b2015-03-17 15:29:32 -07006812void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006813 const DeviceTypeSet& deviceTypes,
6814 int delayMs,
6815 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006816{
jiabincd510522020-01-22 09:40:55 -08006817 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006818 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6819 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6820 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07006821 curves.getVolumeIndex(deviceTypes),
6822 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006823 }
6824}
6825
François Gaffiec005e562018-11-06 15:04:49 +01006826void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6827 bool on,
6828 const sp<AudioOutputDescriptor>& outputDesc,
6829 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006830 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006831{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006832 std::vector<VolumeSource> sourcesToMute;
6833 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6834 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6835 toString(attributes).c_str(), on, outputDesc->getId());
6836 VolumeSource source = toVolumeSource(attributes);
6837 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
6838 sourcesToMute.push_back(source);
6839 }
Eric Laurente552edb2014-03-10 17:42:56 -07006840 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006841 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07006842 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006843 }
6844
Eric Laurente552edb2014-03-10 17:42:56 -07006845}
6846
François Gaffieaaac0fd2018-11-22 17:56:39 +01006847void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6848 bool on,
6849 const sp<AudioOutputDescriptor>& outputDesc,
6850 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006851 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006852{
jiabin9a3361e2019-10-01 09:38:30 -07006853 if (deviceTypes.empty()) {
6854 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006855 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006856 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006857 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006858 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006859 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006860 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6861 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6862 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07006863 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006864 }
6865 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006866 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6867 // ignored
6868 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006869 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006870 if (!outputDesc->isMuted(volumeSource)) {
6871 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006872 return;
6873 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006874 if (outputDesc->decMuteCount(volumeSource) == 0) {
6875 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07006876 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006877 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006878 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006879 delayMs);
6880 }
6881 }
6882}
6883
François Gaffie53615e22015-03-19 09:24:12 +01006884bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6885{
François Gaffiec005e562018-11-06 15:04:49 +01006886 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006887 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6888 return true;
6889 }
6890
6891 // has known usage?
6892 switch (paa->usage) {
6893 case AUDIO_USAGE_UNKNOWN:
6894 case AUDIO_USAGE_MEDIA:
6895 case AUDIO_USAGE_VOICE_COMMUNICATION:
6896 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6897 case AUDIO_USAGE_ALARM:
6898 case AUDIO_USAGE_NOTIFICATION:
6899 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6900 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6901 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6902 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6903 case AUDIO_USAGE_NOTIFICATION_EVENT:
6904 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6905 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6906 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6907 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006908 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006909 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006910 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006911 case AUDIO_USAGE_EMERGENCY:
6912 case AUDIO_USAGE_SAFETY:
6913 case AUDIO_USAGE_VEHICLE_STATUS:
6914 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006915 break;
6916 default:
6917 return false;
6918 }
6919 return true;
6920}
6921
François Gaffie2110e042015-03-24 08:41:51 +01006922audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6923{
6924 return mEngine->getForceUse(usage);
6925}
6926
6927bool AudioPolicyManager::isInCall()
6928{
6929 return isStateInCall(mEngine->getPhoneState());
6930}
6931
6932bool AudioPolicyManager::isStateInCall(int state)
6933{
6934 return is_state_in_call(state);
6935}
6936
Eric Laurent74b71512019-11-06 17:21:57 -08006937bool AudioPolicyManager::isCallAudioAccessible()
6938{
6939 audio_mode_t mode = mEngine->getPhoneState();
6940 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006941 || (mode == AUDIO_MODE_CALL_SCREEN)
6942 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08006943}
6944
Eric Laurentd60560a2015-04-10 11:31:20 -07006945void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6946{
6947 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006948 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006949 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006950 sourceDesc->sinkDevice()->equals(deviceDesc))
6951 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006952 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006953 }
6954 }
6955
6956 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6957 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6958 bool release = false;
6959 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6960 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6961 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6962 source->ext.device.type == deviceDesc->type()) {
6963 release = true;
6964 }
6965 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006966 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07006967 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6968 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6969 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006970 sink->ext.device.type == deviceDesc->type() &&
6971 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
6972 || strncmp(sink->ext.device.address, address,
6973 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006974 release = true;
6975 }
6976 }
6977 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006978 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6979 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006980 }
6981 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006982
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006983 mInputs.clearSessionRoutesForDevice(deviceDesc);
6984
Francois Gaffie716e1432019-01-14 16:58:59 +01006985 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006986}
6987
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006988void AudioPolicyManager::modifySurroundFormats(
6989 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006990 std::unordered_set<audio_format_t> enforcedSurround(
6991 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006992 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6993 for (const auto& pair : mConfig.getSurroundFormats()) {
6994 allSurround.insert(pair.first);
6995 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6996 }
Phil Burk09bc4612016-02-24 15:58:15 -08006997
6998 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6999 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007000 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007001 // This is the resulting set of formats depending on the surround mode:
7002 // 'all surround' = allSurround
7003 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7004 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7005 // 'manual surround' = mManualSurroundFormats
7006 // AUTO: formats v 'enforced surround'
7007 // ALWAYS: formats v 'all surround' v 'enforced surround'
7008 // NEVER: formats ^ 'non-surround'
7009 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007010
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007011 std::unordered_set<audio_format_t> formatSet;
7012 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7013 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007014 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007015 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007016 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007017 formatSet.insert(*formatIter);
7018 }
7019 }
7020 } else {
7021 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7022 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007023 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007024
jiabin81772902018-04-02 17:52:27 -07007025 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007026 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007027 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7028 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7029 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007030 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007031 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7032 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7033 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007034 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007035 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007036 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007037 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007038 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007039 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007040}
7041
jiabin06e4bab2019-07-29 10:13:34 -07007042void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7043 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007044 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7045 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7046
7047 // If NEVER, then remove support for channelMasks > stereo.
7048 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007049 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7050 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007051 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007052 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007053 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007054 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007055 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007056 }
7057 }
jiabin81772902018-04-02 17:52:27 -07007058 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7059 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7060 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007061 bool supports5dot1 = false;
7062 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007063 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007064 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7065 supports5dot1 = true;
7066 break;
7067 }
7068 }
7069 // If not then add 5.1 support.
7070 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007071 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007072 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007073 }
Phil Burk09bc4612016-02-24 15:58:15 -08007074 }
7075}
7076
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007077void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007078 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007079 AudioProfileVector &profiles)
7080{
7081 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007082 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007083
François Gaffie112b0af2015-11-19 16:13:25 +01007084 // Format MUST be checked first to update the list of AudioProfile
7085 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007086 reply = mpClientInterface->getParameters(
7087 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007088 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007089 AudioParameter repliedParameters(reply);
7090 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007091 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007092 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7093 return;
7094 }
Phil Burk09bc4612016-02-24 15:58:15 -08007095 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007096 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007097 if (device == AUDIO_DEVICE_OUT_HDMI
7098 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007099 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007100 }
jiabin3e277cc2019-09-10 14:27:34 -07007101 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007102 }
François Gaffie112b0af2015-11-19 16:13:25 +01007103
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007104 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007105 ChannelMaskSet channelMasks;
7106 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007107 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007108 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007109
7110 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007111 reply = mpClientInterface->getParameters(
7112 ioHandle,
7113 requestedParameters.toString() + ";" +
7114 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007115 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007116 AudioParameter repliedParameters(reply);
7117 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007118 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007119 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007120 }
7121 }
7122 if (profiles.hasDynamicChannelsFor(format)) {
7123 reply = mpClientInterface->getParameters(ioHandle,
7124 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007125 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007126 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007127 AudioParameter repliedParameters(reply);
7128 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007129 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007130 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007131 if (device == AUDIO_DEVICE_OUT_HDMI
7132 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007133 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007134 }
François Gaffie112b0af2015-11-19 16:13:25 +01007135 }
7136 }
jiabin3e277cc2019-09-10 14:27:34 -07007137 addDynamicAudioProfileAndSort(
7138 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007139 }
7140}
Eric Laurentd60560a2015-04-10 11:31:20 -07007141
Mikhail Naganovdc769682018-05-04 15:34:08 -07007142status_t AudioPolicyManager::installPatch(const char *caller,
7143 audio_patch_handle_t *patchHandle,
7144 AudioIODescriptorInterface *ioDescriptor,
7145 const struct audio_patch *patch,
7146 int delayMs)
7147{
7148 ssize_t index = mAudioPatches.indexOfKey(
7149 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7150 *patchHandle : ioDescriptor->getPatchHandle());
7151 sp<AudioPatch> patchDesc;
7152 status_t status = installPatch(
7153 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7154 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007155 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007156 }
7157 return status;
7158}
7159
7160status_t AudioPolicyManager::installPatch(const char *caller,
7161 ssize_t index,
7162 audio_patch_handle_t *patchHandle,
7163 const struct audio_patch *patch,
7164 int delayMs,
7165 uid_t uid,
7166 sp<AudioPatch> *patchDescPtr)
7167{
7168 sp<AudioPatch> patchDesc;
7169 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7170 if (index >= 0) {
7171 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007172 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007173 }
7174
7175 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7176 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7177 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7178 if (status == NO_ERROR) {
7179 if (index < 0) {
7180 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007181 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007182 } else {
7183 patchDesc->mPatch = *patch;
7184 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007185 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007186 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007187 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007188 }
7189 nextAudioPortGeneration();
7190 mpClientInterface->onAudioPatchListUpdate();
7191 }
7192 if (patchDescPtr) *patchDescPtr = patchDesc;
7193 return status;
7194}
7195
jiabinbce0c1d2020-10-05 11:20:18 -07007196bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7197{
7198 const TrackClientVector activeClients = output->getActiveClients();
7199 if (activeClients.empty()) {
7200 return true;
7201 }
7202 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7203 if (index < 0) {
7204 ALOGE("%s, no audio patch found while there are active clients on output %d",
7205 __func__, output->getId());
7206 return false;
7207 }
7208 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7209 DeviceVector routedDevices;
7210 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7211 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7212 patchDesc->mPatch.sinks[i].id);
7213 if (device == nullptr) {
7214 ALOGE("%s, no audio device found with id(%d)",
7215 __func__, patchDesc->mPatch.sinks[i].id);
7216 return false;
7217 }
7218 routedDevices.add(device);
7219 }
7220 for (const auto& client : activeClients) {
7221 // TODO: b/175343099 only travel the valid client
7222 sp<DeviceDescriptor> preferredDevice =
7223 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7224 if (mEngine->getOutputDevicesForAttributes(
7225 client->attributes(), preferredDevice, false) == routedDevices) {
7226 return false;
7227 }
7228 }
7229 return true;
7230}
7231
7232sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
7233 const sp<IOProfile>& profile, const DeviceVector& devices)
7234{
7235 for (const auto& device : devices) {
7236 // TODO: This should be checking if the profile supports the device combo.
7237 if (!profile->supportsDevice(device)) {
7238 return nullptr;
7239 }
7240 }
7241 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7242 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02007243 status_t status = desc->open(nullptr /* halConfig */, nullptr /* mixerConfig */, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007244 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7245 if (status != NO_ERROR) {
7246 return nullptr;
7247 }
7248
7249 // Here is where the out_set_parameters() for card & device gets called
7250 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7251 const audio_devices_t deviceType = device->type();
7252 const String8 &address = String8(device->address().c_str());
7253 if (!address.isEmpty()) {
7254 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7255 mpClientInterface->setParameters(output, String8(param));
7256 free(param);
7257 }
7258 updateAudioProfiles(device, output, profile->getAudioProfiles());
7259 if (!profile->hasValidAudioProfile()) {
7260 ALOGW("%s() missing param", __func__);
7261 desc->close();
7262 return nullptr;
7263 } else if (profile->hasDynamicAudioProfile()) {
7264 desc->close();
7265 output = AUDIO_IO_HANDLE_NONE;
7266 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7267 profile->pickAudioProfile(
7268 config.sample_rate, config.channel_mask, config.format);
7269 config.offload_info.sample_rate = config.sample_rate;
7270 config.offload_info.channel_mask = config.channel_mask;
7271 config.offload_info.format = config.format;
7272
Eric Laurentf1f22e72021-07-13 14:04:14 +02007273 status = desc->open(&config, nullptr /* mixerConfig */, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007274 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7275 if (status != NO_ERROR) {
7276 return nullptr;
7277 }
7278 }
7279
7280 addOutput(output, desc);
7281 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7282 sp<AudioPolicyMix> policyMix;
7283 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7284 policyMix->setOutput(desc);
7285 desc->mPolicyMix = policyMix;
7286 } else {
7287 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7288 address.string());
7289 }
7290
7291 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && hasPrimaryOutput()) {
7292 // no duplicated output for direct outputs and
7293 // outputs used by dynamic policy mixes
7294 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7295
7296 //TODO: configure audio effect output stage here
7297
7298 // open a duplicating output thread for the new output and the primary output
7299 sp<SwAudioOutputDescriptor> dupOutputDesc =
7300 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7301 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7302 if (status == NO_ERROR) {
7303 // add duplicated output descriptor
7304 addOutput(duplicatedOutput, dupOutputDesc);
7305 } else {
7306 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7307 mPrimaryOutput->mIoHandle, output);
7308 desc->close();
7309 removeOutput(output);
7310 nextAudioPortGeneration();
7311 return nullptr;
7312 }
7313 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007314 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7315 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7316 mPrimaryOutput = desc;
7317 }
jiabinbce0c1d2020-10-05 11:20:18 -07007318 return desc;
7319}
7320
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007321} // namespace android