blob: 7185435475e0543f406584700a6d93c8dab38f96 [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>
Eric Laurente552edb2014-03-10 17:42:56 -070034#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080035#include <set>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080036#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110037#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070038
39#include <Serializer.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070040#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070041#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070042#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070043#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070044#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070045#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070046#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070047#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070048#include <utils/Log.h>
49
Eric Laurentd4692962014-05-05 18:13:44 -070050#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010051#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070052
Eric Laurent3b73df72014-03-11 09:06:29 -070053namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070054
Philip P. Moltmannbda45752020-07-17 16:41:18 -070055using media::permission::Identity;
56
Eric Laurentdc462862016-07-19 12:29:53 -070057//FIXME: workaround for truncated touch sounds
58// to be removed when the problem is handled by system UI
59#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070060
61// Largest difference in dB on earpiece in call between the voice volume and another
62// media / notification / system volume.
63constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
64
Mikhail Naganov15be9d22017-11-08 14:18:13 +110065// Compressed formats for MSD module, ordered from most preferred to least preferred.
Dean Wheatley8bee85a2021-02-10 16:02:23 +110066static const std::vector<audio_format_t> msdCompressedFormatsOrder = {{
67 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Mikhail Naganov15be9d22017-11-08 14:18:13 +110068 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
69// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
Dean Wheatley8bee85a2021-02-10 16:02:23 +110070static const std::vector<audio_channel_mask_t> msdSurroundChannelMasksOrder = {{
Mikhail Naganov15be9d22017-11-08 14:18:13 +110071 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
72 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
73 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
74
jiabin06e4bab2019-07-29 10:13:34 -070075template <typename T>
76bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
77{
78 if (left.size() != right.size()) {
79 return false;
80 }
81 for (size_t index = 0; index < right.size(); index++) {
82 if (left[index] != right[index]) {
83 return false;
84 }
85 }
86 return true;
87}
88
89template <typename T>
90bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
91{
92 return !(left == right);
93}
94
Eric Laurente552edb2014-03-10 17:42:56 -070095// ----------------------------------------------------------------------------
96// AudioPolicyInterface implementation
97// ----------------------------------------------------------------------------
98
Eric Laurente0720872014-03-11 09:30:41 -070099status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -0800100 audio_policy_dev_state_t state,
101 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800102 const char *device_name,
103 audio_format_t encodedFormat)
Eric Laurente552edb2014-03-10 17:42:56 -0700104{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800105 status_t status = setDeviceConnectionStateInt(device, state, device_address,
106 device_name, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800107 nextAudioPortGeneration();
108 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800109}
110
François Gaffie11d30102018-11-02 16:09:09 +0100111void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
112 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200113{
jiabince9f20e2019-09-12 16:29:15 -0700114 AudioParameter param(String8(device->address().c_str()));
François Gaffie44481e72016-04-20 07:49:57 +0200115 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganovf23fcf62019-07-08 15:28:43 -0700116 AudioParameter::keyDeviceConnect : AudioParameter::keyDeviceDisconnect);
François Gaffie11d30102018-11-02 16:09:09 +0100117 param.addInt(key, device->type());
François Gaffie44481e72016-04-20 07:49:57 +0200118 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
119}
120
François Gaffie11d30102018-11-02 16:09:09 +0100121status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800122 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800123 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800124 const char *device_name,
125 audio_format_t encodedFormat)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800126{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800127 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s format 0x%X",
128 deviceType, state, device_address, device_name, encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700129
130 // connect/disconnect only 1 device at a time
François Gaffie11d30102018-11-02 16:09:09 +0100131 if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -0700132
François Gaffie11d30102018-11-02 16:09:09 +0100133 sp<DeviceDescriptor> device =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800134 mHwModules.getDeviceDescriptor(deviceType, device_address, device_name, encodedFormat,
Francois Gaffie716e1432019-01-14 16:58:59 +0100135 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700136 return device ? setDeviceConnectionStateInt(device, state) : INVALID_OPERATION;
137}
Paul McLeane743a472015-01-28 11:07:31 -0800138
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700139status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
140 audio_policy_dev_state_t state)
141{
Eric Laurente552edb2014-03-10 17:42:56 -0700142 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700143 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700144 SortedVector <audio_io_handle_t> outputs;
145
François Gaffie11d30102018-11-02 16:09:09 +0100146 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700147
Eric Laurente552edb2014-03-10 17:42:56 -0700148 // save a copy of the opened output descriptors before any output is opened or closed
149 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
150 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700151 switch (state)
152 {
153 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800154 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700155 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100156 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700157 return INVALID_OPERATION;
158 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800159 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700160 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700161
Eric Laurente552edb2014-03-10 17:42:56 -0700162 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200163 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700164 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700165 }
166
François Gaffie44481e72016-04-20 07:49:57 +0200167 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
168 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100169 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200170
François Gaffie11d30102018-11-02 16:09:09 +0100171 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
172 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200173
Francois Gaffie716e1432019-01-14 16:58:59 +0100174 mHwModules.cleanUpForDevice(device);
175
François Gaffie11d30102018-11-02 16:09:09 +0100176 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700177 return INVALID_OPERATION;
178 }
François Gaffie2110e042015-03-24 08:41:51 +0100179
jiabin1c4794b2020-05-05 10:08:05 -0700180 // Populate encapsulation information when a output device is connected.
181 device->setEncapsulationInfoFromHal(mpClientInterface);
182
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700183 // outputs should never be empty here
184 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
185 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100186 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800187
Eric Laurent3ae5f312015-02-03 17:12:08 -0800188 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700189 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700190 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100192 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700193 return INVALID_OPERATION;
194 }
195
François Gaffie11d30102018-11-02 16:09:09 +0100196 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700197
Paul McLeane743a472015-01-28 11:07:31 -0800198 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100199 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700200
Eric Laurente552edb2014-03-10 17:42:56 -0700201 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100202 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700203
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100204 mOutputs.clearSessionRoutesForDevice(device);
205
François Gaffie11d30102018-11-02 16:09:09 +0100206 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100207
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800208 // Reset active device codec
209 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
210
Kriti Dangef6be8f2020-11-05 11:58:19 +0100211 // remove device from mReportedFormatsMap cache
212 mReportedFormatsMap.erase(device);
213
Eric Laurente552edb2014-03-10 17:42:56 -0700214 } break;
215
216 default:
François Gaffie11d30102018-11-02 16:09:09 +0100217 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700218 return BAD_VALUE;
219 }
220
Eric Laurent736a1022019-03-27 18:28:46 -0700221 // Propagate device availability to Engine
222 setEngineDeviceConnectionState(device, state);
223
Eric Laurentae970022019-01-29 14:25:04 -0800224 // No need to evaluate playback routing when connecting a remote submix
225 // output device used by a dynamic policy of type recorder as no
226 // playback use case is affected.
227 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700228 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800229 for (audio_io_handle_t output : outputs) {
230 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800231 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
232 if (policyMix != nullptr
233 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700234 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800235 doCheckForDeviceAndOutputChanges = false;
236 break;
237 }
238 }
239 }
240
241 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700242 // outputs must be closed after checkOutputForAllStrategies() is executed
243 if (!outputs.isEmpty()) {
244 for (audio_io_handle_t output : outputs) {
245 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100246 // close unused outputs after device disconnection or direct outputs that have
247 // been opened by checkOutputsForDevice() to query dynamic parameters
Mikhail Naganov37977152018-07-11 15:54:44 -0700248 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
249 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurentae970022019-01-29 14:25:04 -0800250 (desc->mDirectOpenCount == 0))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200251 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700252 closeOutput(output);
253 }
Eric Laurente552edb2014-03-10 17:42:56 -0700254 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700255 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
256 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700257 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700258 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800259 };
260
261 if (doCheckForDeviceAndOutputChanges) {
262 checkForDeviceAndOutputChanges(checkCloseOutputs);
263 } else {
264 checkCloseOutputs();
265 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100266 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700267 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100268 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700269 const DeviceVector activeMediaDevices =
270 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700271 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700272 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530273 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
274 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100275 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700276 // do not force device change on duplicated output because if device is 0, it will
277 // also force a device 0 for the two outputs it is duplicated to which may override
278 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100279 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100280 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700281 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700282 // always force when disconnecting (a non-duplicated device)
283 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100284 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700285 }
jiabinbce0c1d2020-10-05 11:20:18 -0700286 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000287 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700288 desc->supportsDevicesForPlayback(activeMediaDevices)) {
289 // Reopen the output to query the dynamic profiles when there is not active
290 // clients or all active clients will be rerouted. Otherwise, set the flag
291 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
292 // can be reopened to query dynamic profiles when all clients are inactive.
293 if (areAllActiveTracksRerouted(desc)) {
294 outputsToReopen.push_back(mOutputs.keyAt(i));
295 } else {
296 desc->mPendingReopenToQueryProfiles = true;
297 }
298 }
299 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
300 // Clear the flag that previously set for re-querying profiles.
301 desc->mPendingReopenToQueryProfiles = false;
302 }
303 }
304 for (const auto& output : outputsToReopen) {
305 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
306 closeOutput(output);
307 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700308 }
309
Eric Laurentd60560a2015-04-10 11:31:20 -0700310 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100311 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700312 }
313
Eric Laurent72aa32f2014-05-30 18:51:48 -0700314 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700315 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700316 } // end if is output device
317
Eric Laurente552edb2014-03-10 17:42:56 -0700318 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700319 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100320 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700321 switch (state)
322 {
323 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700324 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700325 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100326 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700327 return INVALID_OPERATION;
328 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700329
330 if (mAvailableInputDevices.add(device) < 0) {
331 return NO_MEMORY;
332 }
333
François Gaffie44481e72016-04-20 07:49:57 +0200334 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
335 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100336 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200337
Eric Laurent0dd51852019-04-19 18:18:58 -0700338 if (checkInputsForDevice(device, state) != NO_ERROR) {
339 mAvailableInputDevices.remove(device);
340
François Gaffie11d30102018-11-02 16:09:09 +0100341 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100342
343 mHwModules.cleanUpForDevice(device);
344
Eric Laurentd4692962014-05-05 18:13:44 -0700345 return INVALID_OPERATION;
346 }
347
Eric Laurentd4692962014-05-05 18:13:44 -0700348 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700349
350 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700351 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700352 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100353 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700354 return INVALID_OPERATION;
355 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700356
François Gaffie11d30102018-11-02 16:09:09 +0100357 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700358
359 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100360 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700361
François Gaffie11d30102018-11-02 16:09:09 +0100362 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700363
364 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100365
366 // remove device from mReportedFormatsMap cache
367 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700368 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700369
370 default:
François Gaffie11d30102018-11-02 16:09:09 +0100371 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700372 return BAD_VALUE;
373 }
374
Eric Laurent736a1022019-03-27 18:28:46 -0700375 // Propagate device availability to Engine
376 setEngineDeviceConnectionState(device, state);
377
Eric Laurent0dd51852019-04-19 18:18:58 -0700378 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700379 // As the input device list can impact the output device selection, update
380 // getDeviceForStrategy() cache
381 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700382
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100383 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200384 // Reconnect Audio Source
385 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
386 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
387 checkAudioSourceForAttributes(attributes);
388 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700389 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100390 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700391 }
392
Eric Laurentb52c1522014-05-20 11:27:36 -0700393 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700394 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700395 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700396
François Gaffie11d30102018-11-02 16:09:09 +0100397 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700398 return BAD_VALUE;
399}
400
Eric Laurent736a1022019-03-27 18:28:46 -0700401void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
402 audio_policy_dev_state_t state) {
403
404 // the Engine does not have to know about remote submix devices used by dynamic audio policies
405 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
406 return;
407 }
408 mEngine->setDeviceConnectionState(device, state);
409}
410
411
Eric Laurente0720872014-03-11 09:30:41 -0700412audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100413 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700414{
Eric Laurent634b7142016-04-20 13:48:02 -0700415 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800416 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
417 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700418 (strlen(device_address) != 0)/*matchAddress*/);
419
420 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100421 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700422 device, device_address);
423 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
424 }
François Gaffie53615e22015-03-19 09:24:12 +0100425
Eric Laurent3a4311c2014-03-17 12:00:47 -0700426 DeviceVector *deviceVector;
427
Eric Laurente552edb2014-03-10 17:42:56 -0700428 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700429 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700430 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700431 deviceVector = &mAvailableInputDevices;
432 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100433 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700434 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700435 }
Eric Laurent634b7142016-04-20 13:48:02 -0700436
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800437 return (deviceVector->getDevice(
438 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700439 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800440}
441
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800442status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
443 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800444 const char *device_name,
445 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800446{
447 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700448 String8 reply;
449 AudioParameter param;
450 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800451
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800452 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
453 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800454
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800455 // connect/disconnect only 1 device at a time
456 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
457
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800458 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700459 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800460 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800461 // Nothing to do: device is not connected
462 return NO_ERROR;
463 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800464 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800465
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700466 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800467 // configure codecs.
468 // Handle two specific cases by sending a set parameter to
469 // configure A2DP codecs. No need to toggle device state.
470 // Case 1: A2DP active device switches from primary to primary
471 // module
472 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200473 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700474 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800475 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
476 if (availablePrimaryOutputDevices().contains(devDesc) &&
477 (module != 0 && module->getHandle() == primaryHandle)) {
478 reply = mpClientInterface->getParameters(
479 AUDIO_IO_HANDLE_NONE,
480 String8(AudioParameter::keyReconfigA2dpSupported));
481 AudioParameter repliedParameters(reply);
482 repliedParameters.getInt(
483 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
484 if (isReconfigA2dpSupported) {
485 const String8 key(AudioParameter::keyReconfigA2dp);
486 param.add(key, String8("true"));
487 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
488 devDesc->setEncodedFormat(encodedFormat);
489 return NO_ERROR;
490 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700491 }
492 }
cnx421bd2dcc42020-07-11 14:58:44 +0800493 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
494 for (size_t i = 0; i < mOutputs.size(); i++) {
495 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
496 // mute media strategies and delay device switch by the largest
497 // This avoid sending the music tail into the earpiece or headset.
498 setStrategyMute(musicStrategy, true, desc);
499 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
500 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
501 nullptr, true /*fromCache*/).types());
502 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800503 // Toggle the device state: UNAVAILABLE -> AVAILABLE
504 // This will force reading again the device configuration
505 status = setDeviceConnectionState(device,
506 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800507 device_address, device_name,
508 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800509 if (status != NO_ERROR) {
510 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
511 status);
512 return status;
513 }
514
515 status = setDeviceConnectionState(device,
516 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800517 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800518 if (status != NO_ERROR) {
519 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
520 status);
521 return status;
522 }
523
524 return NO_ERROR;
525}
526
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800527status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
528 std::vector<audio_format_t> *formats)
529{
530 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800531 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800532 std::unordered_set<audio_format_t> formatSet;
533 sp<HwModule> primaryModule =
534 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700535 if (primaryModule == nullptr) {
536 ALOGE("%s() unable to get primary module", __func__);
537 return NO_INIT;
538 }
jiabin9a3361e2019-10-01 09:38:30 -0700539 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
540 getAudioDeviceOutAllA2dpSet());
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800541 for (const auto& device : declaredDevices) {
542 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800543 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800544 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800545 return status;
546}
547
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100548DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
549{
550 DeviceVector rxSinkdevices{};
551 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
552 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
553 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
554 auto rxSinkDevice = rxSinkdevices.itemAt(0);
555 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
556 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
557 // retrieve Rx Source device descriptor
558 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
559 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
560
561 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
562 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
563 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
564 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
565 return DeviceVector(rxSinkDevice);
566 }
567 }
568 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
569 // the device returned is not necessarily reachable via this output
570 // (filter later by setOutputDevices())
571 return getNewOutputDevices(mPrimaryOutput, fromCache);
572}
573
574status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
575{
576 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
577 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
578 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
579 }
580 return INVALID_OPERATION;
581}
582
583status_t AudioPolicyManager::updateCallRoutingInternal(
584 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700585{
586 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100587 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700588 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700589 if(!hasPrimaryOutput() ||
590 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100591 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700592 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100593 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100594
Francois Gaffie716e1432019-01-14 16:58:59 +0100595 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100596 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100597 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100598
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100599 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100600 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700601
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200602 disconnectTelephonyRxAudioSource();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700603 // release TX patch if any
604 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100605 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700606 mCallTxPatch.clear();
607 }
608
François Gaffie9eb18552018-11-05 10:33:26 +0100609 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700610 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100611 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700612 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100613 // retrieve Rx Source and Tx Sink device descriptors
614 sp<DeviceDescriptor> rxSourceDevice =
615 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
616 String8(),
617 AUDIO_FORMAT_DEFAULT);
618 sp<DeviceDescriptor> txSinkDevice =
619 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
620 String8(),
621 AUDIO_FORMAT_DEFAULT);
622
623 // RX and TX Telephony device are declared by Primary Audio HAL
624 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
625 (telephonyRxModule->getHalVersionMajor() >= 3)) {
626 if (rxSourceDevice == 0 || txSinkDevice == 0) {
627 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100628 ALOGE("%s() no telephony Tx and/or RX device", __func__);
629 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100630 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100631 // createAudioPatchInternal now supports both HW / SW bridging
632 createRxPatch = true;
633 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100634 } else {
635 // If the RX device is on the primary HW module, then use legacy routing method for
636 // voice calls via setOutputDevice() on primary output.
637 // Otherwise, create two audio patches for TX and RX path.
638 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
639 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700640 // If the TX device is also on the primary HW module, setOutputDevice() will take care
641 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100642 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
643 (txSinkDevice != 0);
644 }
645 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
646 // Otherwise, create two audio patches for TX and RX path.
647 if (!createRxPatch) {
648 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700649 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200650 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800651 // If the TX device is on the primary HW module but RX device is
652 // on other HW module, SinkMetaData of telephony input should handle it
653 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700654 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700655 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100656 // terminate active capture if on the same HW module as the call TX source device
657 // FIXME: would be better to refine to only inputs whose profile connects to the
658 // call TX device but this information is not in the audio patch and logic here must be
659 // symmetric to the one in startInput()
660 for (const auto& activeDesc : mInputs.getActiveInputs()) {
661 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
662 closeActiveClients(activeDesc);
663 }
664 }
François Gaffie9eb18552018-11-05 10:33:26 +0100665 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800666 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100667 if (waitMs != nullptr) {
668 *waitMs = muteWaitMs;
669 }
670 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800671}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700672
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800673sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100674 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700675 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700676
François Gaffie11d30102018-11-02 16:09:09 +0100677 if (device == nullptr) {
678 return nullptr;
679 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100680
681 // @TODO: still ignoring the address, or not dealing platform with multiple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800682 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100683 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800684 addSource(mAvailableInputDevices.getDevice(
685 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800686 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100687 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800688 addSink(mAvailableOutputDevices.getDevice(
689 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800690 }
691
François Gaffieafd4cea2019-11-18 15:50:22 +0100692 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
693 status_t status =
694 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
695 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
696 if (status != NO_ERROR || index < 0) {
697 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
698 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800699 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100700 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800701}
702
Mikhail Naganov100f0122018-11-29 11:22:16 -0800703bool AudioPolicyManager::isDeviceOfModule(
704 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
705 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
706 if (module != 0) {
707 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
708 .indexOf(devDesc) != NAME_NOT_FOUND
709 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
710 .indexOf(devDesc) != NAME_NOT_FOUND;
711 }
712 return false;
713}
714
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200715void AudioPolicyManager::connectTelephonyRxAudioSource()
716{
717 disconnectTelephonyRxAudioSource();
718 const struct audio_port_config source = {
719 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
720 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
721 };
722 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
723 status_t status = startAudioSource(&source, &aa, &mCallRxSourceClientPort, 0/*uid*/);
724 ALOGE_IF(status != NO_ERROR, "%s failed to start Telephony Rx AudioSource", __func__);
725}
726
727void AudioPolicyManager::disconnectTelephonyRxAudioSource()
728{
729 stopAudioSource(mCallRxSourceClientPort);
730 mCallRxSourceClientPort = AUDIO_PORT_HANDLE_NONE;
731}
732
Eric Laurente0720872014-03-11 09:30:41 -0700733void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700734{
735 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100736 // store previous phone state for management of sonification strategy below
737 int oldState = mEngine->getPhoneState();
738
739 if (mEngine->setPhoneState(state) != NO_ERROR) {
740 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700741 return;
742 }
François Gaffie2110e042015-03-24 08:41:51 +0100743 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700744 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700745 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700746 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800747 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700748 }
749
François Gaffie2110e042015-03-24 08:41:51 +0100750 /**
751 * Switching to or from incall state or switching between telephony and VoIP lead to force
752 * routing command.
753 */
Eric Laurent74b71512019-11-06 17:21:57 -0800754 bool force = ((isStateInCall(oldState) != isStateInCall(state))
755 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700756
757 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700758 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700759
Eric Laurente552edb2014-03-10 17:42:56 -0700760 int delayMs = 0;
761 if (isStateInCall(state)) {
762 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100763 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
764 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700765 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700766 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700767 // mute media and sonification strategies and delay device switch by the largest
768 // latency of any output where either strategy is active.
769 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100770 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
771 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
772 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700773 (delayMs < (int)desc->latency()*2)) {
774 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700775 }
François Gaffiec005e562018-11-06 15:04:49 +0100776 setStrategyMute(musicStrategy, true, desc);
777 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
778 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
779 nullptr, true /*fromCache*/).types());
780 setStrategyMute(sonificationStrategy, true, desc);
781 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
782 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
783 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700784 }
785 }
786
Eric Laurent87ffa392015-05-22 10:32:38 -0700787 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700788 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100789 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700790 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100791 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
792 // force routing command to audio hardware when ending call
793 // even if no device change is needed
794 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
795 rxDevices = mPrimaryOutput->devices();
796 }
797 if (oldState == AUDIO_MODE_IN_CALL) {
798 disconnectTelephonyRxAudioSource();
799 if (mCallTxPatch != 0) {
800 releaseAudioPatchInternal(mCallTxPatch->getHandle());
801 mCallTxPatch.clear();
802 }
803 }
François Gaffie11d30102018-11-02 16:09:09 +0100804 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700805 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700806 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700807
808 // reevaluate routing on all outputs in case tracks have been started during the call
809 for (size_t i = 0; i < mOutputs.size(); i++) {
810 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100811 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700812 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100813 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700814 }
815 }
816
Eric Laurente552edb2014-03-10 17:42:56 -0700817 if (isStateInCall(state)) {
818 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700819 // force reevaluating accessibility routing when call starts
820 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700821 }
822
823 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100824 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
825 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700826}
827
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700828audio_mode_t AudioPolicyManager::getPhoneState() {
829 return mEngine->getPhoneState();
830}
831
Eric Laurente0720872014-03-11 09:30:41 -0700832void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100833 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700834{
François Gaffie2110e042015-03-24 08:41:51 +0100835 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700836 if (config == mEngine->getForceUse(usage)) {
837 return;
838 }
Eric Laurente552edb2014-03-10 17:42:56 -0700839
François Gaffie2110e042015-03-24 08:41:51 +0100840 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
841 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
842 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700843 }
François Gaffie2110e042015-03-24 08:41:51 +0100844 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
845 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
846 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700847
848 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700849 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800850
Eric Laurent22fcda22019-05-17 16:28:47 -0700851 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
852 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
853 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
854 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
855 }
856
Eric Laurentdc462862016-07-19 12:29:53 -0700857 //FIXME: workaround for truncated touch sounds
858 // to be removed when the problem is handled by system UI
859 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700860 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
861 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
862 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700863
864 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100865 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700866}
867
Eric Laurente0720872014-03-11 09:30:41 -0700868void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700869{
870 ALOGV("setSystemProperty() property %s, value %s", property, value);
871}
872
Michael Chana94fbb22018-04-24 14:31:19 +1000873// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
874// search to profiles for direct outputs.
875sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100876 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000877 uint32_t samplingRate,
878 audio_format_t format,
879 audio_channel_mask_t channelMask,
880 audio_output_flags_t flags,
881 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700882{
Michael Chana94fbb22018-04-24 14:31:19 +1000883 if (directOnly) {
884 // only retain flags that will drive the direct output profile selection
885 // if explicitly requested
886 static const uint32_t kRelevantFlags =
887 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lataba810b82019-07-03 11:15:33 -0700888 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000889 flags =
890 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
891 }
Eric Laurent861a6282015-05-18 15:40:16 -0700892
893 sp<IOProfile> profile;
894
Mikhail Naganovd4120142017-12-06 15:49:22 -0800895 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800896 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100897 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700898 samplingRate, NULL /*updatedSamplingRate*/,
899 format, NULL /*updatedFormat*/,
900 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700901 flags)) {
902 continue;
903 }
904 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100905 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700906 continue;
907 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800908 // reject profiles if connected device does not support codec
jiabin9a3361e2019-10-01 09:38:30 -0700909 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800910 continue;
911 }
Michael Chana94fbb22018-04-24 14:31:19 +1000912 if (!directOnly) return curProfile;
913 // when searching for direct outputs, if several profiles are compatible, give priority
914 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100915 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700916 continue;
917 }
918 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100919 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700920 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700921 }
Eric Laurente552edb2014-03-10 17:42:56 -0700922 }
923 }
Eric Laurent861a6282015-05-18 15:40:16 -0700924 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700925}
926
Eric Laurentf4e63452017-11-06 19:31:46 +0000927audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700928{
François Gaffiec005e562018-11-06 15:04:49 +0100929 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800930
931 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
932 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
933 // format, flags, etc. This may result in some discrepancy for functions that utilize
934 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
935 // and AudioSystem::getOutputSamplingRate().
936
François Gaffie11d30102018-11-02 16:09:09 +0100937 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700938 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700939
François Gaffie11d30102018-11-02 16:09:09 +0100940 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
941 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000942 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700943}
944
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700945status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
946 const audio_attributes_t *srcAttr,
947 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700948{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700949 if (srcAttr != NULL) {
950 if (!isValidAttributes(srcAttr)) {
951 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
952 __func__,
953 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
954 srcAttr->tags);
955 return BAD_VALUE;
956 }
957 *dstAttr = *srcAttr;
958 } else {
959 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
960 ALOGE("%s: invalid stream type", __func__);
961 return BAD_VALUE;
962 }
François Gaffiec005e562018-11-06 15:04:49 +0100963 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700964 }
Eric Laurent22fcda22019-05-17 16:28:47 -0700965
966 // Only honor audibility enforced when required. The client will be
967 // forced to reconnect if the forced usage changes.
968 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700969 dstAttr->flags = static_cast<audio_flags_mask_t>(
970 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -0700971 }
972
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700973 return NO_ERROR;
974}
975
Kevin Rocard153f92d2018-12-18 18:33:28 -0800976status_t AudioPolicyManager::getOutputForAttrInt(
977 audio_attributes_t *resultAttr,
978 audio_io_handle_t *output,
979 audio_session_t session,
980 const audio_attributes_t *attr,
981 audio_stream_type_t *stream,
982 uid_t uid,
983 const audio_config_t *config,
984 audio_output_flags_t *flags,
985 audio_port_handle_t *selectedDeviceId,
986 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -0700987 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -0800988 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700989{
François Gaffiec005e562018-11-06 15:04:49 +0100990 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +0100991 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100992 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +0100993 const sp<DeviceDescriptor> requestedDevice =
994 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
995
Eric Laurent8a1095a2019-11-08 14:44:16 -0800996 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700997 status_t status = getAudioAttributes(resultAttr, attr, *stream);
998 if (status != NO_ERROR) {
999 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001000 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001001 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001002 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001003 }
François Gaffiec005e562018-11-06 15:04:49 +01001004 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001005
François Gaffiec005e562018-11-06 15:04:49 +01001006 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1007 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001008
Kevin Rocard153f92d2018-12-18 18:33:28 -08001009 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1010 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1011 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001012 sp<AudioPolicyMix> primaryMix;
1013 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001014 if (status != OK) {
1015 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001016 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001017
Kevin Rocard153f92d2018-12-18 18:33:28 -08001018 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001019 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001020
1021 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -07001022 if ((usePrimaryOutputFromPolicyMixes
1023 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -08001024 && !audio_is_linear_pcm(config->format)) {
1025 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001026 return BAD_VALUE;
1027 }
1028 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001029 sp<DeviceDescriptor> deviceDesc =
1030 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1031 primaryMix->mDeviceAddress,
1032 AUDIO_FORMAT_DEFAULT);
1033 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001034 if (deviceDesc != nullptr
1035 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001036 audio_io_handle_t newOutput;
1037 status = openDirectOutput(
1038 *stream, session, config,
1039 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1040 DeviceVector(deviceDesc), &newOutput);
1041 if (status != NO_ERROR) {
1042 policyDesc = nullptr;
1043 } else {
1044 policyDesc = mOutputs.valueFor(newOutput);
1045 primaryMix->setOutput(policyDesc);
1046 }
1047 }
1048 if (policyDesc != nullptr) {
1049 policyDesc->mPolicyMix = primaryMix;
1050 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001051 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001052
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001053 ALOGV("getOutputForAttr() returns output %d", *output);
1054 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1055 *outputType = API_OUT_MIX_PLAYBACK;
1056 } else {
1057 *outputType = API_OUTPUT_LEGACY;
1058 }
1059 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001060 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001061 }
François Gaffiec005e562018-11-06 15:04:49 +01001062 // Virtual sources must always be dynamicaly or explicitly routed
1063 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1064 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1065 return BAD_VALUE;
1066 }
1067 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1068 // in order to let the choice of the order to future vendor engine
1069 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001070
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001071 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001072 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001073 }
1074
Nadav Barb2f18162018-07-18 13:01:53 +03001075 // Set incall music only if device was explicitly set, and fallback to the device which is
1076 // chosen by the engine if not.
1077 // FIXME: provide a more generic approach which is not device specific and move this back
1078 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001079 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001080 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001081 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001082 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001083 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001084 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001085 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001086 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001087 }
1088 }
1089
François Gaffiec005e562018-11-06 15:04:49 +01001090 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1091 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1092 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001093
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001094 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001095 if (!msdDevices.isEmpty()) {
1096 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001097 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001098 ALOGV("%s() Using MSD devices %s instead of devices %s",
1099 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001100 } else {
1101 *output = AUDIO_IO_HANDLE_NONE;
1102 }
1103 }
1104 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabine375d412019-02-26 12:54:53 -08001105 *output = getOutputForDevices(outputDevices, session, *stream, config,
Eric Laurent42984412019-05-09 17:57:03 -07001106 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001107 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001108 if (*output == AUDIO_IO_HANDLE_NONE) {
1109 return INVALID_OPERATION;
1110 }
Paul McLeanaa981192015-03-21 09:55:15 -07001111
François Gaffiec005e562018-11-06 15:04:49 +01001112 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001113 for (auto &outputDevice : outputDevices) {
1114 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1115 *selectedDeviceId = outputDevice->getId();
1116 break;
1117 }
1118 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001119
Eric Laurent8a1095a2019-11-08 14:44:16 -08001120 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1121 *outputType = API_OUTPUT_TELEPHONY_TX;
1122 } else {
1123 *outputType = API_OUTPUT_LEGACY;
1124 }
1125
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001126 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1127
1128 return NO_ERROR;
1129}
1130
1131status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1132 audio_io_handle_t *output,
1133 audio_session_t session,
1134 audio_stream_type_t *stream,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001135 const Identity& identity,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001136 const audio_config_t *config,
1137 audio_output_flags_t *flags,
1138 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001139 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001140 std::vector<audio_io_handle_t> *secondaryOutputs,
1141 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001142{
1143 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1144 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1145 return INVALID_OPERATION;
1146 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001147 const uid_t uid = VALUE_OR_RETURN_STATUS(
1148 aidl2legacy_int32_t_uid_t(identity.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001149 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001150 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001151 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001152 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001153 const sp<DeviceDescriptor> requestedDevice =
1154 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1155
1156 // Prevent from storing invalid requested device id in clients
1157 const audio_port_handle_t sanitizedRequestedPortId =
1158 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1159 *selectedDeviceId = sanitizedRequestedPortId;
1160
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001161 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001162 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001163 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001164 if (status != NO_ERROR) {
1165 return status;
1166 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001167 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001168 if (secondaryOutputs != nullptr) {
1169 for (auto &secondaryMix : secondaryMixes) {
1170 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1171 if (outputDesc != nullptr &&
1172 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1173 secondaryOutputs->push_back(outputDesc->mIoHandle);
1174 weakSecondaryOutputDescs.push_back(outputDesc);
1175 }
1176 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001177 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001178
Eric Laurent8fc147b2018-07-22 19:13:55 -07001179 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001180 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001181 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001182 };
jiabin4ef93452019-09-10 14:29:54 -07001183 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001184
Eric Laurentc209fe42020-06-05 18:11:23 -07001185 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001186 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001187 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001188 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001189 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001190 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001191 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001192 std::move(weakSecondaryOutputDescs),
1193 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001194 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001195
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001196 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1197 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001198
Eric Laurente83b55d2014-11-14 10:06:21 -08001199 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001200}
1201
Eric Laurentc529cf62020-04-17 18:19:10 -07001202status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1203 audio_session_t session,
1204 const audio_config_t *config,
1205 audio_output_flags_t flags,
1206 const DeviceVector &devices,
1207 audio_io_handle_t *output) {
1208
1209 *output = AUDIO_IO_HANDLE_NONE;
1210
1211 // skip direct output selection if the request can obviously be attached to a mixed output
1212 // and not explicitly requested
1213 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1214 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1215 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1216 return NAME_NOT_FOUND;
1217 }
1218
1219 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1220 // This prevents creating an offloaded track and tearing it down immediately after start
1221 // when audioflinger detects there is an active non offloadable effect.
1222 // FIXME: We should check the audio session here but we do not have it in this context.
1223 // This may prevent offloading in rare situations where effects are left active by apps
1224 // in the background.
1225 sp<IOProfile> profile;
1226 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1227 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1228 profile = getProfileForOutput(
1229 devices, config->sample_rate, config->format, config->channel_mask,
1230 flags, true /* directOnly */);
1231 }
1232
1233 if (profile == nullptr) {
1234 return NAME_NOT_FOUND;
1235 }
1236
1237 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1238 for (size_t i = 0; i < mOutputs.size(); i++) {
1239 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1240 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1241 // reuse direct output if currently open by the same client
1242 // and configured with same parameters
1243 if ((config->sample_rate == desc->getSamplingRate()) &&
1244 (config->format == desc->getFormat()) &&
1245 (config->channel_mask == desc->getChannelMask()) &&
1246 (session == desc->mDirectClientSession)) {
1247 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001248 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001249 mOutputs.keyAt(i), session);
1250 *output = mOutputs.keyAt(i);
1251 return NO_ERROR;
1252 }
1253 }
1254 }
1255
1256 if (!profile->canOpenNewIo()) {
1257 return NAME_NOT_FOUND;
1258 }
1259
1260 sp<SwAudioOutputDescriptor> outputDesc =
1261 new SwAudioOutputDescriptor(profile, mpClientInterface);
1262
Michael Chan6fb34492020-12-08 15:44:49 +11001263 // An MSD patch may be using the only output stream that can service this request. Release
1264 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001265 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001266
1267 status_t status = outputDesc->open(config, devices, stream, flags, output);
1268
1269 // only accept an output with the requested parameters
1270 if (status != NO_ERROR ||
1271 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1272 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1273 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1274 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1275 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1276 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1277 config->channel_mask, outputDesc->getChannelMask());
1278 if (*output != AUDIO_IO_HANDLE_NONE) {
1279 outputDesc->close();
1280 }
1281 // fall back to mixer output if possible when the direct output could not be open
1282 if (audio_is_linear_pcm(config->format) &&
1283 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1284 return NAME_NOT_FOUND;
1285 }
1286 *output = AUDIO_IO_HANDLE_NONE;
1287 return BAD_VALUE;
1288 }
1289 outputDesc->mDirectOpenCount = 1;
1290 outputDesc->mDirectClientSession = session;
1291
1292 addOutput(*output, outputDesc);
1293 mPreviousOutputs = mOutputs;
1294 ALOGV("%s returns new direct output %d", __func__, *output);
1295 mpClientInterface->onAudioPortListUpdate();
1296 return NO_ERROR;
1297}
1298
François Gaffie11d30102018-11-02 16:09:09 +01001299audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1300 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001301 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001302 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001303 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001304 audio_output_flags_t *flags,
1305 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001306{
Andy Hungc88b0642018-04-27 15:42:35 -07001307 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001308
jiabine375d412019-02-26 12:54:53 -08001309 // Discard haptic channel mask when forcing muting haptic channels.
1310 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001311 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1312 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001313
Eric Laurente552edb2014-03-10 17:42:56 -07001314 // open a direct output if required by specified parameters
1315 //force direct flag if offload flag is set: offloading implies a direct output stream
1316 // and all common behaviors are driven by checking only the direct flag
1317 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001318 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1319 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001320 }
Nadav Bar766fb022018-01-07 12:18:03 +02001321 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1322 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001323 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001324 // only allow deep buffering for music stream type
1325 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001326 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001327 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001328 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001329 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1330 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001331 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001332 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001333 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001334 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001335 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001336 audio_is_linear_pcm(config->format) &&
1337 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001338 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001339 AUDIO_OUTPUT_FLAG_DIRECT);
1340 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001341 }
Eric Laurente552edb2014-03-10 17:42:56 -07001342
Eric Laurentc529cf62020-04-17 18:19:10 -07001343 audio_config_t directConfig = *config;
1344 directConfig.channel_mask = channelMask;
1345 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1346 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001347 return output;
1348 }
1349
Eric Laurent14cbfca2016-03-17 09:42:16 -07001350 // A request for HW A/V sync cannot fallback to a mixed output because time
1351 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001352 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001353 return AUDIO_IO_HANDLE_NONE;
1354 }
1355
Eric Laurente552edb2014-03-10 17:42:56 -07001356 // ignoring channel mask due to downmix capability in mixer
1357
1358 // open a non direct output
1359
1360 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001361 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001362 // get which output is suitable for the specified stream. The actual
1363 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001364 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001365
Eric Laurent8838a382014-09-08 16:44:28 -07001366 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001367 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001368 output = selectOutput(
1369 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001370 }
François Gaffie11d30102018-11-02 16:09:09 +01001371 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001372 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001373 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001374
Eric Laurente552edb2014-03-10 17:42:56 -07001375 return output;
1376}
1377
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001378sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001379 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1380 mAvailableInputDevices);
1381 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1382}
1383
1384DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1385 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1386 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001387}
1388
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001389const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001390 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001391 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1392 if (msdModule != 0) {
1393 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1394 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1395 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1396 const struct audio_port_config *source = &patch->mPatch.sources[j];
1397 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1398 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001399 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001400 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001401 }
1402 }
1403 }
1404 return msdPatches;
1405}
1406
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001407status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1408 const InputProfileCollection &inputProfiles,
1409 const OutputProfileCollection &outputProfiles,
1410 const sp<DeviceDescriptor> &sourceDevice,
1411 const sp<DeviceDescriptor> &sinkDevice,
1412 AudioProfileVector& sourceProfiles,
1413 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001414 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001415 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001416 return NO_INIT;
1417 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001418 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001419 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001420 return NO_INIT;
1421 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001422 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001423 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1424 inProfile->supportsDevice(sourceDevice)) {
1425 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001426 }
1427 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001428 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001429 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001430 outProfile->supportsDevice(sinkDevice)) {
1431 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001432 }
1433 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001434 return NO_ERROR;
1435}
1436
1437status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1438 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1439 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1440{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001441 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001442 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1443 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1444 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001445 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001446 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1447 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001448 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001449 }
1450 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1451 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1452 sinkConfig->format = bestSinkConfig.format;
1453 // For encoded streams force direct flag to prevent downstream mixing.
1454 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1455 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001456 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1457 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001458 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001459 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1460 // raw and IEC61937 framed streams.
1461 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1462 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1463 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001464 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1465 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1466 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1467 sourceConfig->format = bestSinkConfig.format;
1468 // Copy input stream directly without any processing (e.g. resampling).
1469 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1470 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1471 if (hwAvSync) {
1472 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1473 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1474 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1475 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1476 }
1477 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1478 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1479 sinkConfig->config_mask |= config_mask;
1480 sourceConfig->config_mask |= config_mask;
1481 return NO_ERROR;
1482}
1483
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001484PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1485 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001486{
1487 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001488 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1489 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1490 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1491 if (deviceModule == nullptr) {
1492 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1493 return patchBuilder;
1494 }
1495 const InputProfileCollection inputProfiles = msdIsSource ?
1496 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1497 const OutputProfileCollection outputProfiles = msdIsSource ?
1498 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1499
1500 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1501 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1502 device : getMsdAudioOutDevices().itemAt(0);
1503 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1504
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001505 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1506 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001507 AudioProfileVector sourceProfiles;
1508 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001509 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1510 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001511 for (auto hwAvSync : { true, false }) {
1512 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1513 sourceProfiles, sinkProfiles) != NO_ERROR) {
1514 continue;
1515 }
1516 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1517 &sinkConfig) == NO_ERROR) {
1518 // Found a matching config. Re-create PatchBuilder with this config.
1519 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1520 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001521 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001522 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001523 " supporting PCM format conversion.", __func__);
1524 return patchBuilder;
1525}
1526
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001527status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001528 DeviceVector devices;
1529 if (outputDevices != nullptr && outputDevices->size() > 0) {
1530 devices.add(*outputDevices);
1531 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001532 // Use media strategy for unspecified output device. This should only
1533 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1534 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001535 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001536 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001537 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001538 }
Michael Chan6fb34492020-12-08 15:44:49 +11001539 std::vector<PatchBuilder> patchesToCreate;
1540 for (auto i = 0u; i < devices.size(); ++i) {
1541 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001542 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001543 }
1544 // Retain only the MSD patches associated with outputDevices request.
1545 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001546 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001547 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1548 auto retainedPatch = false;
1549 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1550 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1551 patchesToRemove.removeItemsAt(i);
1552 retainedPatch = true;
1553 break;
1554 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001555 }
Michael Chan6fb34492020-12-08 15:44:49 +11001556 if (retainedPatch) {
1557 it = patchesToCreate.erase(it);
1558 continue;
1559 }
1560 ++it;
1561 }
1562 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1563 return NO_ERROR;
1564 }
1565 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1566 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001567 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001568 }
Michael Chan6fb34492020-12-08 15:44:49 +11001569 status_t status = NO_ERROR;
1570 for (const auto &p : patchesToCreate) {
1571 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1572 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1573 char message[256];
1574 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1575 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1576 currStatus == NO_ERROR ? "Success" : "Error",
1577 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1578 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1579 if (currStatus == NO_ERROR) {
1580 ALOGD("%s", message);
1581 } else {
1582 ALOGE("%s", message);
1583 if (status == NO_ERROR) {
1584 status = currStatus;
1585 }
1586 }
1587 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001588 return status;
1589}
1590
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001591void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1592 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001593 for (size_t i = 0; i < msdPatches.size(); i++) {
1594 const auto& patch = msdPatches[i];
1595 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1596 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1597 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1598 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1599 releaseAudioPatch(patch->getHandle(), mUidCached);
1600 break;
1601 }
1602 }
1603 }
1604}
1605
Eric Laurente0720872014-03-11 09:30:41 -07001606audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001607 audio_output_flags_t flags,
1608 audio_format_t format,
1609 audio_channel_mask_t channelMask,
1610 uint32_t samplingRate,
1611 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001612{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001613 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1614 "%s called with format %#x", __func__, format);
1615
jiabinebb6af42020-06-09 17:31:17 -07001616 // Return the output that haptic-generating attached to when 1) session id is specified,
1617 // 2) haptic-generating effect exists for given session id and 3) the output that
1618 // haptic-generating effect attached to is in given outputs.
1619 if (sessionId != AUDIO_SESSION_NONE) {
1620 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1621 sessionId, FX_IID_HAPTICGENERATOR);
1622 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1623 return hapticGeneratingOutput;
1624 }
1625 }
1626
Eric Laurent16c66dd2019-05-01 17:54:10 -07001627 // Flags disqualifying an output: the match must happen before calling selectOutput()
1628 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1629 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1630
1631 // Flags expressing a functional request: must be honored in priority over
1632 // other criteria
1633 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1634 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1635 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1636 // Flags expressing a performance request: have lower priority than serving
1637 // requested sampling rate or channel mask
1638 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1639 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1640 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1641
1642 const audio_output_flags_t functionalFlags =
1643 (audio_output_flags_t)(flags & kFunctionalFlags);
1644 const audio_output_flags_t performanceFlags =
1645 (audio_output_flags_t)(flags & kPerformanceFlags);
1646
1647 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1648
Eric Laurente552edb2014-03-10 17:42:56 -07001649 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001650 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001651 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001652 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001653 // 2: the output with the highest number of requested functional flags
1654 // 3: the output supporting the exact channel mask
1655 // 4: the output with a higher channel count than requested
1656 // 5: the output with a higher sampling rate than requested
1657 // 6: the output with the highest number of requested performance flags
1658 // 7: the output with the bit depth the closest to the requested one
1659 // 8: the primary output
1660 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001661
Eric Laurent16c66dd2019-05-01 17:54:10 -07001662 // matching criteria values in priority order for best matching output so far
1663 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001664
Eric Laurent16c66dd2019-05-01 17:54:10 -07001665 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1666 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1667 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001668
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001669 for (audio_io_handle_t output : outputs) {
1670 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001671 // matching criteria values in priority order for current output
1672 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001673
Eric Laurent16c66dd2019-05-01 17:54:10 -07001674 if (outputDesc->isDuplicated()) {
1675 continue;
1676 }
1677 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1678 continue;
1679 }
Eric Laurent8838a382014-09-08 16:44:28 -07001680
Eric Laurent16c66dd2019-05-01 17:54:10 -07001681 // If haptic channel is specified, use the haptic output if present.
1682 // When using haptic output, same audio format and sample rate are required.
1683 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001684 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001685 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1686 continue;
1687 }
1688 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001689 && format == outputDesc->getFormat()
1690 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001691 currentMatchCriteria[0] = outputHapticChannelCount;
1692 }
1693
1694 // functional flags match
1695 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1696
1697 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001698 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1699 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001700 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1701 channelCount <= outputChannelCount) {
1702 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001703 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1704 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001705 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001706 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001707 currentMatchCriteria[3] = outputChannelCount;
1708 }
1709
1710 // sampling rate match
1711 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001712 samplingRate <= outputDesc->getSamplingRate()) {
1713 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001714 }
1715
1716 // performance flags match
1717 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1718
1719 // format match
1720 if (format != AUDIO_FORMAT_INVALID) {
1721 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001722 PolicyAudioPort::kFormatDistanceMax -
1723 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001724 }
1725
1726 // primary output match
1727 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1728
1729 // compare match criteria by priority then value
1730 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1731 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1732 bestMatchCriteria = currentMatchCriteria;
1733 bestOutput = output;
1734
1735 std::stringstream result;
1736 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1737 std::ostream_iterator<int>(result, " "));
1738 ALOGV("%s new bestOutput %d criteria %s",
1739 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001740 }
1741 }
1742
Eric Laurent16c66dd2019-05-01 17:54:10 -07001743 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001744}
1745
Eric Laurent8fc147b2018-07-22 19:13:55 -07001746status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001747{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001748 ALOGV("%s portId %d", __FUNCTION__, portId);
1749
1750 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1751 if (outputDesc == 0) {
1752 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001753 return BAD_VALUE;
1754 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001755 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001756
Eric Laurent8fc147b2018-07-22 19:13:55 -07001757 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001758 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001759
Eric Laurent733ce942017-12-07 12:18:25 -08001760 status_t status = outputDesc->start();
1761 if (status != NO_ERROR) {
1762 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001763 }
1764
Eric Laurent97ac8712018-07-27 18:59:02 -07001765 uint32_t delayMs;
1766 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001767
1768 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001769 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001770 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001771 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001772 if (delayMs != 0) {
1773 usleep(delayMs * 1000);
1774 }
1775
1776 return status;
1777}
1778
Eric Laurent97ac8712018-07-27 18:59:02 -07001779status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1780 const sp<TrackClientDescriptor>& client,
1781 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001782{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001783 // cannot start playback of STREAM_TTS if any other output is being used
1784 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001785
1786 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001787 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001788 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001789 auto clientStrategy = client->strategy();
1790 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001791 if (stream == AUDIO_STREAM_TTS) {
1792 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001793 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001794 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001795 return INVALID_OPERATION;
1796 } else {
1797 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1798 }
1799 } else {
1800 // some playback other than beacon starts
1801 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1802 }
1803
Eric Laurent77305a62016-07-25 16:39:22 -07001804 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001805 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001806 bool force = !outputDesc->isActive() &&
1807 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001808
François Gaffie11d30102018-11-02 16:09:09 +01001809 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001810 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001811 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001812 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001813 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001814 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001815 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001816 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001817 } else {
1818 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001819 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001820 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1821 AUDIO_FORMAT_DEFAULT);
1822 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1823 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001824 }
1825
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001826 // requiresMuteCheck is false when we can bypass mute strategy.
1827 // It covers a common case when there is no materially active audio
1828 // and muting would result in unnecessary delay and dropped audio.
1829 const uint32_t outputLatencyMs = outputDesc->latency();
1830 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1831
Eric Laurente552edb2014-03-10 17:42:56 -07001832 // increment usage count for this stream on the requested output:
1833 // NOTE that the usage count is the same for duplicated output and hardware output which is
1834 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001835 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001836
1837 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001838 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1839 client->isPreferredDeviceForExclusiveUse()) {
1840 // Preferred device may be exclusive, use only if no other active clients on this output
1841 devices = DeviceVector(
1842 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1843 } else {
1844 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1845 }
François Gaffie11d30102018-11-02 16:09:09 +01001846 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001847 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001848 }
1849 }
Eric Laurente552edb2014-03-10 17:42:56 -07001850
François Gaffiec005e562018-11-06 15:04:49 +01001851 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001852 selectOutputForMusicEffects();
1853 }
1854
François Gaffie1c878552018-11-22 16:53:21 +01001855 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001856 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001857 if (devices.isEmpty()) {
1858 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001859 }
François Gaffiec005e562018-11-06 15:04:49 +01001860 bool shouldWait =
1861 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1862 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1863 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001864 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001865 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001866 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001867 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001868 // An output has a shared device if
1869 // - managed by the same hw module
1870 // - supports the currently selected device
1871 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001872 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001873
Eric Laurent77305a62016-07-25 16:39:22 -07001874 // force a device change if any other output is:
1875 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001876 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001877 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001878 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001879 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001880 // change the device currently selected by the other output.
1881 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001882 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001883 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001884 force = true;
1885 }
1886 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001887 // a notification so that audio focus effect can propagate, or that a mute/unmute
1888 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001889 const uint32_t latencyMs = desc->latency();
1890 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1891
1892 if (shouldWait && isActive && (waitMs < latencyMs)) {
1893 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001894 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001895
1896 // Require mute check if another output is on a shared device
1897 // and currently active to have proper drain and avoid pops.
1898 // Note restoring AudioTracks onto this output needs to invoke
1899 // a volume ramp if there is no mute.
1900 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001901 }
1902 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001903
1904 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001905 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001906
Eric Laurente552edb2014-03-10 17:42:56 -07001907 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001908 auto &curves = getVolumeCurves(client->attributes());
1909 checkAndSetVolume(curves, client->volumeSource(),
1910 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001911 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001912 outputDesc->devices().types(), 0 /*delay*/,
1913 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001914
1915 // update the outputs if starting an output with a stream that can affect notification
1916 // routing
1917 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001918
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001919 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001920 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001921 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1922 }
Eric Laurentdc462862016-07-19 12:29:53 -07001923
1924 if (waitMs > muteWaitMs) {
1925 *delayMs = waitMs - muteWaitMs;
1926 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001927
1928 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1929 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1930 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1931 // change occurs after the MixerThread starts and causes a stream volume
1932 // glitch.
1933 //
1934 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001935 }
Eric Laurentdc462862016-07-19 12:29:53 -07001936
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001937 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07001938 mEngine->getForceUse(
1939 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001940 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001941 }
1942
Eric Laurent97ac8712018-07-27 18:59:02 -07001943 // Automatically enable the remote submix input when output is started on a re routing mix
1944 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07001945 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1946 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001947 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1948 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1949 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001950 "remote-submix",
1951 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001952 }
1953
Eric Laurente552edb2014-03-10 17:42:56 -07001954 return NO_ERROR;
1955}
1956
Eric Laurent8fc147b2018-07-22 19:13:55 -07001957status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001958{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001959 ALOGV("%s portId %d", __FUNCTION__, portId);
1960
1961 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1962 if (outputDesc == 0) {
1963 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001964 return BAD_VALUE;
1965 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001966 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001967
Eric Laurent97ac8712018-07-27 18:59:02 -07001968 ALOGV("stopOutput() output %d, stream %d, session %d",
1969 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001970
Eric Laurent97ac8712018-07-27 18:59:02 -07001971 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001972
Eric Laurent733ce942017-12-07 12:18:25 -08001973 if (status == NO_ERROR ) {
1974 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001975 }
1976 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001977}
1978
Eric Laurent97ac8712018-07-27 18:59:02 -07001979status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1980 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001981{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001982 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001983 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001984 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07001985
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001986 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1987
François Gaffie1c878552018-11-22 16:53:21 +01001988 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
1989 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001990 // Automatically disable the remote submix input when output is stopped on a
1991 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001992 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07001993 if (isSingleDeviceType(
1994 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001995 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001996 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001997 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1998 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001999 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002000 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002001 }
2002 }
2003 bool forceDeviceUpdate = false;
2004 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002005 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002006 forceDeviceUpdate = true;
2007 }
2008
Eric Laurente552edb2014-03-10 17:42:56 -07002009 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002010 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002011
Eric Laurente552edb2014-03-10 17:42:56 -07002012 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002013 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002014 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002015 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002016 // delay the device switch by twice the latency because stopOutput() is executed when
2017 // the track stop() command is received and at that time the audio track buffer can
2018 // still contain data that needs to be drained. The latency only covers the audio HAL
2019 // and kernel buffers. Also the latency does not always include additional delay in the
2020 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01002021 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07002022
2023 // force restoring the device selection on other active outputs if it differs from the
2024 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002025 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002026 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002027 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002028 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002029 desc->isActive() &&
2030 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002031 (newDevices != desc->devices())) {
2032 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2033 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002034
François Gaffie11d30102018-11-02 16:09:09 +01002035 setOutputDevices(desc, newDevices2, force, delayMs);
2036
Eric Laurent57de36c2016-09-28 16:59:11 -07002037 // re-apply device specific volume if not done by setOutputDevice()
2038 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002039 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002040 }
Eric Laurente552edb2014-03-10 17:42:56 -07002041 }
2042 }
2043 // update the outputs if stopping one with a stream that can affect notification routing
2044 handleNotificationRoutingForStream(stream);
2045 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002046
2047 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2048 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002049 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002050 }
2051
François Gaffiec005e562018-11-06 15:04:49 +01002052 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002053 selectOutputForMusicEffects();
2054 }
Eric Laurente552edb2014-03-10 17:42:56 -07002055 return NO_ERROR;
2056 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002057 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002058 return INVALID_OPERATION;
2059 }
2060}
2061
jiabinbce0c1d2020-10-05 11:20:18 -07002062bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002063{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002064 ALOGV("%s portId %d", __FUNCTION__, portId);
2065
2066 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2067 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002068 // If an output descriptor is closed due to a device routing change,
2069 // then there are race conditions with releaseOutput from tracks
2070 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2071 // destroyed shortly thereafter.
2072 //
2073 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002074 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002075 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002076 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002077
2078 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002079
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302080 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2081 if (outputDesc->isClientActive(client)) {
2082 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2083 stopOutput(portId);
2084 }
2085
Eric Laurent8fc147b2018-07-22 19:13:55 -07002086 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2087 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002088 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002089 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002090 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002091 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002092 if (--outputDesc->mDirectOpenCount == 0) {
2093 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002094 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002095 }
2096 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302097
Andy Hung39efb7a2018-09-26 15:39:28 -07002098 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002099 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2100 // The output is pending reopened to query dynamic profiles and
2101 // there is no active clients
2102 closeOutput(outputDesc->mIoHandle);
2103 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2104 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2105 if (newOutputDesc == nullptr) {
2106 ALOGE("%s failed to open output", __func__);
2107 }
2108 return true;
2109 }
2110 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002111}
2112
Eric Laurentcaf7f482014-11-25 17:50:47 -08002113status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2114 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002115 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002116 audio_session_t session,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002117 const Identity& identity,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002118 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002119 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002120 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002121 input_type_t *inputType,
2122 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002123{
François Gaffiec005e562018-11-06 15:04:49 +01002124 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
2125 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
2126 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002127
Eric Laurentad2e7b92017-09-14 20:06:42 -07002128 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002129 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002130 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002131 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002132 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002133 sp<AudioInputDescriptor> inputDesc;
2134 sp<RecordClientDescriptor> clientDesc;
2135 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002136 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(identity.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002137 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002138
2139 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2140 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2141 return INVALID_OPERATION;
2142 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002143
Francois Gaffie716e1432019-01-14 16:58:59 +01002144 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2145 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002146 }
2147
Paul McLean466dc8e2015-04-17 13:15:36 -06002148 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01002149 sp<DeviceDescriptor> explicitRoutingDevice =
2150 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002151
Eric Laurentad2e7b92017-09-14 20:06:42 -07002152 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2153 // possible
2154 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2155 *input != AUDIO_IO_HANDLE_NONE) {
2156 ssize_t index = mInputs.indexOfKey(*input);
2157 if (index < 0) {
2158 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2159 status = BAD_VALUE;
2160 goto error;
2161 }
2162 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002163 RecordClientVector clients = inputDesc->getClientsForSession(session);
2164 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002165 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2166 status = BAD_VALUE;
2167 goto error;
2168 }
2169 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2170 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002171 // corresponds to a new client and is only permitted from the same UID.
2172 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002173 if (clients.size() > 1) {
2174 for (const auto& client : clients) {
2175 // The client map is ordered by key values (portId) and portIds are allocated
2176 // incrementaly. So the first client in this list is the one opened by audio flinger
2177 // when the mmap stream is created and should be ignored as it does not correspond
2178 // to an actual client
2179 if (client == *clients.cbegin()) {
2180 continue;
2181 }
2182 if (uid != client->uid() && !client->isSilenced()) {
2183 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2184 uid, client->portId(), client->uid());
2185 status = INVALID_OPERATION;
2186 goto error;
2187 }
Eric Laurent331679c2018-04-16 17:03:16 -07002188 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002189 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002190 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002191 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002192
Eric Laurentfecbceb2021-02-09 14:46:43 +01002193 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002194 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002195 }
2196
2197 *input = AUDIO_IO_HANDLE_NONE;
2198 *inputType = API_INPUT_INVALID;
2199
Francois Gaffie716e1432019-01-14 16:58:59 +01002200 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002201
Francois Gaffie716e1432019-01-14 16:58:59 +01002202 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2203 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2204 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002205 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002206 ALOGW("%s could not find input mix for attr %s",
2207 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002208 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002209 }
jiabinc1de2df2019-05-07 14:26:40 -07002210 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2211 String8(attr->tags + strlen("addr=")),
2212 AUDIO_FORMAT_DEFAULT);
2213 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002214 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002215 __func__, attributes.source, attributes.tags);
2216 status = BAD_VALUE;
2217 goto error;
2218 }
2219
Kevin Rocard25f9b052019-02-27 15:08:54 -08002220 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2221 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2222 } else {
2223 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2224 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002225 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002226 if (explicitRoutingDevice != nullptr) {
2227 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002228 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002229 // Prevent from storing invalid requested device id in clients
2230 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002231 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002232 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2233 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002234 }
François Gaffie11d30102018-11-02 16:09:09 +01002235 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002236 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002237 status = BAD_VALUE;
2238 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002239 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002240 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2241 *inputType = API_INPUT_MIX_CAPTURE;
2242 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002243 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2244 // there is an external policy, but this input is attached to a mix of recorders,
2245 // meaning it receives audio injected into the framework, so the recorder doesn't
2246 // know about it and is therefore considered "legacy"
2247 *inputType = API_INPUT_LEGACY;
2248 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002249 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002250 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002251 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002252 } else {
2253 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002254 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002255
Eric Laurent599c7582015-12-07 18:05:55 -08002256 }
2257
François Gaffiec005e562018-11-06 15:04:49 +01002258 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002259 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002260 status = INVALID_OPERATION;
2261 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002262 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002263
Eric Laurent8f42ea12018-08-08 09:08:25 -07002264exit:
2265
François Gaffiec005e562018-11-06 15:04:49 +01002266 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2267 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002268
Francois Gaffie716e1432019-01-14 16:58:59 +01002269 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002270 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002271 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002272
Mikhail Naganov2996f672019-04-18 12:29:59 -07002273 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002274 requestedDeviceId, attributes.source, flags,
2275 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002276 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002277 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002278
2279 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2280 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002281
Eric Laurent599c7582015-12-07 18:05:55 -08002282 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002283
2284error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002285 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002286}
2287
2288
François Gaffie11d30102018-11-02 16:09:09 +01002289audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002290 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002291 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002292 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002293 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002294 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002295{
2296 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002297 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002298 bool isSoundTrigger = false;
2299
François Gaffiec005e562018-11-06 15:04:49 +01002300 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002301 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2302 if (index >= 0) {
2303 input = mSoundTriggerSessions.valueFor(session);
2304 isSoundTrigger = true;
2305 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2306 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2307 } else {
2308 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002309 }
François Gaffiec005e562018-11-06 15:04:49 +01002310 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002311 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002312 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002313 }
2314
Andy Hungf129b032015-04-07 13:45:50 -07002315 // find a compatible input profile (not necessarily identical in parameters)
2316 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002317 // sampling rate and flags may be updated by getInputProfile
2318 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2319 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002320 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002321 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002322 audio_input_flags_t profileFlags = flags;
2323 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002324 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002325 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002326 profileFlags);
2327 if (profile != 0) {
2328 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002329 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2330 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002331 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2332 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2333 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002334 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2335 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2336 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002337 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002338 }
Eric Laurente552edb2014-03-10 17:42:56 -07002339 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002340 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002341 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002342 if (samplingRate == 0) {
2343 samplingRate = profileSamplingRate;
2344 }
Eric Laurente552edb2014-03-10 17:42:56 -07002345
Eric Laurent322b4d22015-04-03 15:57:54 -07002346 if (profile->getModuleHandle() == 0) {
2347 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002348 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002349 }
2350
Eric Laurentec376dc2021-04-08 20:41:22 +02002351 // Reuse an already opened input if a client with the same session ID already exists
2352 // on that input
2353 for (size_t i = 0; i < mInputs.size(); i++) {
2354 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2355 if (desc->mProfile != profile) {
2356 continue;
2357 }
2358 RecordClientVector clients = desc->clientsList();
2359 for (const auto &client : clients) {
2360 if (session == client->session()) {
2361 return desc->mIoHandle;
2362 }
2363 }
2364 }
2365
Eric Laurent3974e3b2017-12-07 17:58:43 -08002366 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002367 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002368 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002369 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002370 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002371 continue;
2372 }
2373 // if sound trigger, reuse input if used by other sound trigger on same session
2374 // else
2375 // reuse input if active client app is not in IDLE state
2376 //
2377 RecordClientVector clients = desc->clientsList();
2378 bool doClose = false;
2379 for (const auto& client : clients) {
2380 if (isSoundTrigger != client->isSoundTrigger()) {
2381 continue;
2382 }
2383 if (client->isSoundTrigger()) {
2384 if (session == client->session()) {
2385 return desc->mIoHandle;
2386 }
2387 continue;
2388 }
2389 if (client->active() && client->appState() != APP_STATE_IDLE) {
2390 return desc->mIoHandle;
2391 }
2392 doClose = true;
2393 }
2394 if (doClose) {
2395 closeInput(desc->mIoHandle);
2396 } else {
2397 i++;
2398 }
2399 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002400 }
2401
Eric Laurentfe231122017-11-17 17:48:06 -08002402 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002403
Eric Laurentfe231122017-11-17 17:48:06 -08002404 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2405 lConfig.sample_rate = profileSamplingRate;
2406 lConfig.channel_mask = profileChannelMask;
2407 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002408
François Gaffie11d30102018-11-02 16:09:09 +01002409 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002410
2411 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002412 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002413 (profileSamplingRate != lConfig.sample_rate) ||
2414 !audio_formats_match(profileFormat, lConfig.format) ||
2415 (profileChannelMask != lConfig.channel_mask)) {
2416 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002417 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002418 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002419 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002420 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002421 }
Eric Laurent599c7582015-12-07 18:05:55 -08002422 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002423 }
2424
Eric Laurentc722f302014-12-10 11:21:49 -08002425 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002426
Eric Laurent599c7582015-12-07 18:05:55 -08002427 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002428 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002429
Eric Laurent599c7582015-12-07 18:05:55 -08002430 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002431}
2432
Eric Laurent4eb58f12018-12-07 16:41:02 -08002433status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002434{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002435 ALOGV("%s portId %d", __FUNCTION__, portId);
2436
2437 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2438 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002439 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002440 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002441 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002442 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002443 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002444 if (client->active()) {
2445 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2446 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002447 }
2448
Eric Laurent8f42ea12018-08-08 09:08:25 -07002449 audio_session_t session = client->session();
2450
Eric Laurent4eb58f12018-12-07 16:41:02 -08002451 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002452
Eric Laurent4eb58f12018-12-07 16:41:02 -08002453 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002454
Eric Laurent4eb58f12018-12-07 16:41:02 -08002455 status_t status = inputDesc->start();
2456 if (status != NO_ERROR) {
2457 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002458 }
Eric Laurente552edb2014-03-10 17:42:56 -07002459
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002460 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002461 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002462 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002463
Eric Laurent8f42ea12018-08-08 09:08:25 -07002464 // indicate active capture to sound trigger service if starting capture from a mic on
2465 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002466 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002467 if (device != nullptr) {
2468 status = setInputDevice(input, device, true /* force */);
2469 } else {
2470 ALOGW("%s no new input device can be found for descriptor %d",
2471 __FUNCTION__, inputDesc->getId());
2472 status = BAD_VALUE;
2473 }
Eric Laurente552edb2014-03-10 17:42:56 -07002474
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002475 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002476 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002477 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002478 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002479 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2480 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002481 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002482 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002483
François Gaffie11d30102018-11-02 16:09:09 +01002484 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2485 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002486 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002487 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002488 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002489
Eric Laurent8f42ea12018-08-08 09:08:25 -07002490 // automatically enable the remote submix output when input is started if not
2491 // used by a policy mix of type MIX_TYPE_RECORDERS
2492 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002493 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002494 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002495 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002496 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002497 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2498 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002499 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002500 if (address != "") {
2501 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2502 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002503 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002504 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002505 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002506 } else if (status != NO_ERROR) {
2507 // Restore client activity state.
2508 inputDesc->setClientActive(client, false);
2509 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002510 }
2511
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002512 ALOGV("%s input %d source = %d status = %d exit",
2513 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002514
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002515 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002516}
2517
Eric Laurent8fc147b2018-07-22 19:13:55 -07002518status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002519{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002520 ALOGV("%s portId %d", __FUNCTION__, portId);
2521
2522 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2523 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002524 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002525 return BAD_VALUE;
2526 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002527 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002528 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002529 if (!client->active()) {
2530 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002531 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002532 }
2533
Eric Laurent8f42ea12018-08-08 09:08:25 -07002534 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002535
Eric Laurent8f42ea12018-08-08 09:08:25 -07002536 inputDesc->stop();
2537 if (inputDesc->isActive()) {
2538 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2539 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002540 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002541 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002542 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002543 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2544 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002545 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002546 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002547
2548 // automatically disable the remote submix output when input is stopped if not
2549 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002550 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002551 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002552 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002553 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002554 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2555 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002556 }
2557 if (address != "") {
2558 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2559 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002560 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002561 }
2562 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002563 resetInputDevice(input);
2564
2565 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2566 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002567 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2568 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002569 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002570 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002571 }
2572 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002573 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002574 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002575}
2576
Eric Laurent8fc147b2018-07-22 19:13:55 -07002577void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002578{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002579 ALOGV("%s portId %d", __FUNCTION__, portId);
2580
2581 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2582 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002583 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002584 return;
2585 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002586 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002587 audio_io_handle_t input = inputDesc->mIoHandle;
2588
Eric Laurent8f42ea12018-08-08 09:08:25 -07002589 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002590
Andy Hung39efb7a2018-09-26 15:39:28 -07002591 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002592
Andy Hung39efb7a2018-09-26 15:39:28 -07002593 if (inputDesc->getClientCount() > 0) {
2594 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002595 return;
2596 }
2597
Eric Laurent05b90f82014-08-27 15:32:29 -07002598 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002599 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002600 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002601}
2602
Eric Laurent8f42ea12018-08-08 09:08:25 -07002603void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002604{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002605 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002606
2607 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002608 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002609 }
2610}
2611
Eric Laurent8f42ea12018-08-08 09:08:25 -07002612void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2613{
2614 stopInput(portId);
2615 releaseInput(portId);
2616}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002617
Eric Laurent0dd51852019-04-19 18:18:58 -07002618void AudioPolicyManager::checkCloseInputs() {
2619 // After connecting or disconnecting an input device, close input if:
2620 // - it has no client (was just opened to check profile) OR
2621 // - none of its supported devices are connected anymore OR
2622 // - one of its clients cannot be routed to one of its supported
2623 // devices anymore. Otherwise update device selection
2624 std::vector<audio_io_handle_t> inputsToClose;
2625 for (size_t i = 0; i < mInputs.size(); i++) {
2626 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2627 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002628 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002629 inputsToClose.push_back(mInputs.keyAt(i));
2630 } else {
2631 bool close = false;
2632 for (const auto& client : input->clientsList()) {
2633 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002634 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002635 if (!input->supportedDevices().contains(device)) {
2636 close = true;
2637 break;
2638 }
2639 }
2640 if (close) {
2641 inputsToClose.push_back(mInputs.keyAt(i));
2642 } else {
2643 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2644 }
2645 }
2646 }
2647
2648 for (const audio_io_handle_t handle : inputsToClose) {
2649 ALOGV("%s closing input %d", __func__, handle);
2650 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002651 }
Eric Laurentd4692962014-05-05 18:13:44 -07002652}
2653
François Gaffie251c7f02018-11-07 10:41:08 +01002654void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002655{
2656 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002657 if (indexMin < 0 || indexMax < 0) {
2658 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2659 return;
2660 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002661 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002662
2663 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002664 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2665 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002666 continue;
2667 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002668 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002669 }
Eric Laurente552edb2014-03-10 17:42:56 -07002670}
2671
Eric Laurente0720872014-03-11 09:30:41 -07002672status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002673 int index,
2674 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002675{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002676 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002677 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2678 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2679 return NO_ERROR;
2680 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002681 ALOGV("%s: stream %s attributes=%s", __func__,
2682 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002683 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002684}
2685
Eric Laurente0720872014-03-11 09:30:41 -07002686status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002687 int *index,
2688 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002689{
François Gaffiec005e562018-11-06 15:04:49 +01002690 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2691 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002692 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002693 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002694 deviceTypes = mEngine->getOutputDevicesForStream(
2695 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002696 }
jiabin9a3361e2019-10-01 09:38:30 -07002697 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002698}
2699
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002700status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002701 int index,
2702 audio_devices_t device)
2703{
2704 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002705 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2706 if (group == VOLUME_GROUP_NONE) {
2707 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002708 return BAD_VALUE;
2709 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002710 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002711 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002712 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002713 VolumeSource vs = toVolumeSource(group);
2714 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2715
2716 status = setVolumeCurveIndex(index, device, curves);
2717 if (status != NO_ERROR) {
2718 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2719 return status;
2720 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002721
jiabin9a3361e2019-10-01 09:38:30 -07002722 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002723 auto curCurvAttrs = curves.getAttributes();
2724 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2725 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002726 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002727 } else if (!curves.getStreamTypes().empty()) {
2728 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002729 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002730 } else {
2731 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2732 return BAD_VALUE;
2733 }
jiabin9a3361e2019-10-01 09:38:30 -07002734 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2735 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002736
François Gaffiecfe17322018-11-07 13:41:29 +01002737 // update volume on all outputs and streams matching the following:
2738 // - The requested stream (or a stream matching for volume control) is active on the output
2739 // - The device (or devices) selected by the engine for this stream includes
2740 // the requested device
2741 // - For non default requested device, currently selected device on the output is either the
2742 // requested device or one of the devices selected by the engine for this stream
2743 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2744 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002745 for (size_t i = 0; i < mOutputs.size(); i++) {
2746 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002747 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002748
jiabin9a3361e2019-10-01 09:38:30 -07002749 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2750 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002751 }
François Gaffieed91f582020-01-31 10:35:37 +01002752 if (!(desc->isActive(vs) || isInCall())) {
2753 continue;
2754 }
2755 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2756 curDevices.find(device) == curDevices.end()) {
2757 continue;
2758 }
2759 bool applyVolume = false;
2760 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2761 curSrcDevices.insert(device);
2762 applyVolume = (curSrcDevices.find(
2763 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2764 } else {
2765 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2766 }
2767 if (!applyVolume) {
2768 continue; // next output
2769 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002770 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2771 // If a higher priority strategy is active, and the output is routed to a device with a
2772 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002773 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002774 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002775 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2776 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2777 false /*preferredDevice*/);
2778 if (activeClients.empty()) {
2779 continue;
2780 }
2781 bool isPreempted = false;
2782 bool isHigherPriority = productStrategy < strategy;
2783 for (const auto &client : activeClients) {
2784 if (isHigherPriority && (client->volumeSource() != vs)) {
2785 ALOGV("%s: Strategy=%d (\nrequester:\n"
2786 " group %d, volumeGroup=%d attributes=%s)\n"
2787 " higher priority source active:\n"
2788 " volumeGroup=%d attributes=%s) \n"
2789 " on output %zu, bailing out", __func__, productStrategy,
2790 group, group, toString(attributes).c_str(),
2791 client->volumeSource(), toString(client->attributes()).c_str(), i);
2792 applyVolume = false;
2793 isPreempted = true;
2794 break;
2795 }
2796 // However, continue for loop to ensure no higher prio clients running on output
2797 if (client->volumeSource() == vs) {
2798 applyVolume = true;
2799 }
2800 }
2801 if (isPreempted || applyVolume) {
2802 break;
2803 }
2804 }
2805 if (!applyVolume) {
2806 continue; // next output
2807 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002808 }
François Gaffieed91f582020-01-31 10:35:37 +01002809 //FIXME: workaround for truncated touch sounds
2810 // delayed volume change for system stream to be removed when the problem is
2811 // handled by system UI
2812 status_t volStatus = checkAndSetVolume(
2813 curves, vs, index, desc, curDevices,
2814 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2815 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2816 if (volStatus != NO_ERROR) {
2817 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002818 }
2819 }
François Gaffiecfe17322018-11-07 13:41:29 +01002820 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2821 return status;
2822}
2823
François Gaffieaaac0fd2018-11-22 17:56:39 +01002824status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002825 audio_devices_t device,
2826 IVolumeCurves &volumeCurves)
2827{
2828 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2829 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002830 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2831 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002832 (index > volumeCurves.getVolumeIndexMax())) {
2833 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2834 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2835 return BAD_VALUE;
2836 }
2837 if (!audio_is_output_device(device)) {
2838 return BAD_VALUE;
2839 }
2840
2841 // Force max volume if stream cannot be muted
2842 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2843
François Gaffieaaac0fd2018-11-22 17:56:39 +01002844 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002845 volumeCurves.addCurrentVolumeIndex(device, index);
2846 return NO_ERROR;
2847}
2848
2849status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2850 int &index,
2851 audio_devices_t device)
2852{
2853 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2854 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002855 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002856 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002857 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2858 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002859 }
jiabin9a3361e2019-10-01 09:38:30 -07002860 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002861}
2862
2863status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2864 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002865 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002866{
jiabin9a3361e2019-10-01 09:38:30 -07002867 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002868 return BAD_VALUE;
2869 }
jiabin9a3361e2019-10-01 09:38:30 -07002870 index = curves.getVolumeIndex(deviceTypes);
2871 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002872 return NO_ERROR;
2873}
2874
2875status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2876 int &index)
2877{
2878 index = getVolumeCurves(attr).getVolumeIndexMin();
2879 return NO_ERROR;
2880}
2881
2882status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2883 int &index)
2884{
2885 index = getVolumeCurves(attr).getVolumeIndexMax();
2886 return NO_ERROR;
2887}
2888
Eric Laurent36829f92017-04-07 19:04:42 -07002889audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002890{
2891 // select one output among several suitable for global effects.
2892 // The priority is as follows:
2893 // 1: An offloaded output. If the effect ends up not being offloadable,
2894 // AudioFlinger will invalidate the track and the offloaded output
2895 // will be closed causing the effect to be moved to a PCM output.
2896 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002897 // 3: The primary output
2898 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002899
François Gaffiec005e562018-11-06 15:04:49 +01002900 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2901 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002902 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002903
Eric Laurent36829f92017-04-07 19:04:42 -07002904 if (outputs.size() == 0) {
2905 return AUDIO_IO_HANDLE_NONE;
2906 }
Eric Laurente552edb2014-03-10 17:42:56 -07002907
Eric Laurent36829f92017-04-07 19:04:42 -07002908 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2909 bool activeOnly = true;
2910
2911 while (output == AUDIO_IO_HANDLE_NONE) {
2912 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2913 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2914 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2915
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002916 for (audio_io_handle_t output : outputs) {
2917 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002918 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002919 continue;
2920 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002921 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2922 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002923 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002924 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002925 }
2926 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002927 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002928 }
2929 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002930 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002931 }
2932 }
2933 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2934 output = outputOffloaded;
2935 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2936 output = outputDeepBuffer;
2937 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2938 output = outputPrimary;
2939 } else {
2940 output = outputs[0];
2941 }
2942 activeOnly = false;
2943 }
2944
2945 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002946 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002947 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2948 mMusicEffectOutput = output;
2949 }
2950
2951 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002952 return output;
2953}
2954
Eric Laurent36829f92017-04-07 19:04:42 -07002955audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2956{
2957 return selectOutputForMusicEffects();
2958}
2959
Eric Laurente0720872014-03-11 09:30:41 -07002960status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002961 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002962 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07002963 int session,
2964 int id)
2965{
Eric Laurentb82e6b72019-11-22 17:25:04 -08002966 if (session != AUDIO_SESSION_DEVICE) {
2967 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07002968 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08002969 index = mInputs.indexOfKey(io);
2970 if (index < 0) {
2971 ALOGW("registerEffect() unknown io %d", io);
2972 return INVALID_OPERATION;
2973 }
Eric Laurente552edb2014-03-10 17:42:56 -07002974 }
2975 }
François Gaffiec005e562018-11-06 15:04:49 +01002976 return mEffects.registerEffect(desc, io, session, id,
2977 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
2978 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07002979}
2980
Eric Laurentc241b0d2018-11-28 09:08:49 -08002981status_t AudioPolicyManager::unregisterEffect(int id)
2982{
2983 if (mEffects.getEffect(id) == nullptr) {
2984 return INVALID_OPERATION;
2985 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08002986 if (mEffects.isEffectEnabled(id)) {
2987 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2988 setEffectEnabled(id, false);
2989 }
2990 return mEffects.unregisterEffect(id);
2991}
2992
2993status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2994{
2995 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2996 if (effect == nullptr) {
2997 return INVALID_OPERATION;
2998 }
2999
3000 status_t status = mEffects.setEffectEnabled(id, enabled);
3001 if (status == NO_ERROR) {
3002 mInputs.trackEffectEnabled(effect, enabled);
3003 }
3004 return status;
3005}
3006
Eric Laurent6c796322019-04-09 14:13:17 -07003007
3008status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3009{
3010 mEffects.moveEffects(ids, io);
3011 return NO_ERROR;
3012}
3013
Eric Laurentc75307b2015-03-17 15:29:32 -07003014bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3015{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003016 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003017}
3018
3019bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3020{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003021 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003022}
3023
Eric Laurente0720872014-03-11 09:30:41 -07003024bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003025{
3026 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003027 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003028 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003029 return true;
3030 }
3031 }
3032 return false;
3033}
3034
Eric Laurent275e8e92014-11-30 15:14:47 -08003035// Register a list of custom mixes with their attributes and format.
3036// When a mix is registered, corresponding input and output profiles are
3037// added to the remote submix hw module. The profile contains only the
3038// parameters (sampling rate, format...) specified by the mix.
3039// The corresponding input remote submix device is also connected.
3040//
3041// When a remote submix device is connected, the address is checked to select the
3042// appropriate profile and the corresponding input or output stream is opened.
3043//
3044// When capture starts, getInputForAttr() will:
3045// - 1 look for a mix matching the address passed in attribtutes tags if any
3046// - 2 if none found, getDeviceForInputSource() will:
3047// - 2.1 look for a mix matching the attributes source
3048// - 2.2 if none found, default to device selection by policy rules
3049// At this time, the corresponding output remote submix device is also connected
3050// and active playback use cases can be transferred to this mix if needed when reconnecting
3051// after AudioTracks are invalidated
3052//
3053// When playback starts, getOutputForAttr() will:
3054// - 1 look for a mix matching the address passed in attribtutes tags if any
3055// - 2 if none found, look for a mix matching the attributes usage
3056// - 3 if none found, default to device and output selection by policy rules.
3057
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003058status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003059{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003060 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3061 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003062 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003063 sp<HwModule> rSubmixModule;
3064 // examine each mix's route type
3065 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003066 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003067 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3068 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3069 ALOGE("Unsupported Policy Mix %zu of %zu: "
3070 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3071 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003072 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003073 break;
3074 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003075 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3076 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003077 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003078 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3079 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003080 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003081 rSubmixModule = mHwModules.getModuleFromName(
3082 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3083 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003084 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003085 i);
3086 res = INVALID_OPERATION;
3087 break;
3088 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003089 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003090
Eric Laurent97ac8712018-07-27 18:59:02 -07003091 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003092 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003093 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003094 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003095 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3096 } else {
3097 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3098 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003099 }
François Gaffie036e1e92015-03-19 10:16:24 +01003100
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003101 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003102 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003103 res = INVALID_OPERATION;
3104 break;
3105 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003106 audio_config_t outputConfig = mix.mFormat;
3107 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003108 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3109 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003110 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3111 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003112 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003113 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003114 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003115 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003116
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003117 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003118 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3119 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3120 ALOGE("Failed to set remote submix device available, type %u, address %s",
3121 mix.mDeviceType, address.string());
3122 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003123 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003124 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3125 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003126 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003127 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003128 i, mixes.size(), type, address.string());
3129
3130 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3131 mix.mDeviceType, mix.mDeviceAddress,
3132 String8(), AUDIO_FORMAT_DEFAULT);
3133 if (device == nullptr) {
3134 res = INVALID_OPERATION;
3135 break;
3136 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003137
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003138 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003139 // First try to find an already opened output supporting the device
3140 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003141 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003142
Eric Laurentc529cf62020-04-17 18:19:10 -07003143 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003144 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003145 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3146 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003147 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003148 } else {
3149 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003150 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003151 }
3152 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003153 // If no output found, try to find a direct output profile supporting the device
3154 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3155 sp<HwModule> module = mHwModules[i];
3156 for (size_t j = 0;
3157 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3158 j++) {
3159 sp<IOProfile> profile = module->getOutputProfiles()[j];
3160 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3161 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3162 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3163 address.string());
3164 res = INVALID_OPERATION;
3165 } else {
3166 foundOutput = true;
3167 }
3168 }
3169 }
3170 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003171 if (res != NO_ERROR) {
3172 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003173 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003174 res = INVALID_OPERATION;
3175 break;
3176 } else if (!foundOutput) {
3177 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003178 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003179 res = INVALID_OPERATION;
3180 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003181 } else {
3182 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003183 }
Eric Laurentc722f302014-12-10 11:21:49 -08003184 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003185 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003186 if (res != NO_ERROR) {
3187 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003188 } else if (checkOutputs) {
3189 checkForDeviceAndOutputChanges();
3190 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003191 }
3192 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003193}
3194
3195status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3196{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003197 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003198 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003199 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003200 sp<HwModule> rSubmixModule;
3201 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003202 for (const auto& mix : mixes) {
3203 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003204
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003205 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003206 rSubmixModule = mHwModules.getModuleFromName(
3207 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3208 if (rSubmixModule == 0) {
3209 res = INVALID_OPERATION;
3210 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003211 }
3212 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003213
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003214 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003215
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003216 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003217 res = INVALID_OPERATION;
3218 continue;
3219 }
3220
Kevin Rocard04ed0462019-05-02 17:53:24 -07003221 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3222 if (getDeviceConnectionState(device, address.string()) ==
3223 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3224 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3225 address.string(), "remote-submix",
3226 AUDIO_FORMAT_DEFAULT);
3227 if (res != OK) {
3228 ALOGE("Error making RemoteSubmix device unavailable for mix "
3229 "with type %d, address %s", device, address.string());
3230 }
3231 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003232 }
jiabin5740f082019-08-19 15:08:30 -07003233 rSubmixModule->removeOutputProfile(address.c_str());
3234 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003235
Kevin Rocard153f92d2018-12-18 18:33:28 -08003236 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003237 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003238 res = INVALID_OPERATION;
3239 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003240 } else {
3241 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003242 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003243 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003244 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003245 if (res == NO_ERROR && checkOutputs) {
3246 checkForDeviceAndOutputChanges();
3247 updateCallAndOutputRouting();
3248 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003249 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003250}
3251
Mikhail Naganov100f0122018-11-29 11:22:16 -08003252void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3253{
3254 size_t i = 0;
3255 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3256 for (const auto& fmt : mManualSurroundFormats) {
3257 if (i++ != 0) dst->append(", ");
3258 std::string sfmt;
3259 FormatConverter::toString(fmt, sfmt);
3260 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3261 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3262 }
3263}
3264
Eric Laurentc529cf62020-04-17 18:19:10 -07003265// Returns true if all devices types match the predicate and are supported by one HW module
3266bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003267 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003268 std::function<bool(audio_devices_t)> predicate,
3269 const char *context) {
3270 for (size_t i = 0; i < devices.size(); i++) {
3271 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003272 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003273 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003274 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003275 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003276 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003277 return false;
3278 }
3279 }
3280 return true;
3281}
3282
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003283status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003284 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003285 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003286 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3287 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003288 }
3289 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003290 if (res != NO_ERROR) {
3291 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3292 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003293 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003294
3295 checkForDeviceAndOutputChanges();
3296 updateCallAndOutputRouting();
3297
3298 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003299}
3300
3301status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3302 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003303 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3304 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003305 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003306 __FUNCTION__, uid);
3307 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003308 }
3309
Eric Laurentc529cf62020-04-17 18:19:10 -07003310 checkForDeviceAndOutputChanges();
3311 updateCallAndOutputRouting();
3312
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003313 return res;
3314}
3315
Eric Laurent2517af32020-11-25 15:31:27 +01003316
jiabin0a488932020-08-07 17:32:40 -07003317status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3318 device_role_t role,
3319 const AudioDeviceTypeAddrVector &devices) {
3320 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3321 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003322
Eric Laurentc529cf62020-04-17 18:19:10 -07003323 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003324 return BAD_VALUE;
3325 }
jiabin0a488932020-08-07 17:32:40 -07003326 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003327 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003328 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3329 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003330 return status;
3331 }
3332
3333 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003334
3335 bool forceVolumeReeval = false;
3336 // FIXME: workaround for truncated touch sounds
3337 // to be removed when the problem is handled by system UI
3338 uint32_t delayMs = 0;
3339 if (strategy == mCommunnicationStrategy) {
3340 forceVolumeReeval = true;
3341 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3342 updateInputRouting();
3343 }
3344 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003345
3346 return NO_ERROR;
3347}
3348
3349void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3350{
3351 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003352 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003353 // Only apply special touch sound delay once
3354 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003355 }
3356 for (size_t i = 0; i < mOutputs.size(); i++) {
3357 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3358 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3359 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3360 // As done in setDeviceConnectionState, we could also fix default device issue by
3361 // preventing the force re-routing in case of default dev that distinguishes on address.
3362 // Let's give back to engine full device choice decision however.
3363 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003364 // Only apply special touch sound delay once
3365 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003366 }
3367 if (forceVolumeReeval && !newDevices.isEmpty()) {
3368 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3369 }
3370 }
3371}
3372
Eric Laurent2517af32020-11-25 15:31:27 +01003373void AudioPolicyManager::updateInputRouting() {
3374 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303375 // Skip for hotword recording as the input device switch
3376 // is handled within sound trigger HAL
3377 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3378 continue;
3379 }
Eric Laurent2517af32020-11-25 15:31:27 +01003380 auto newDevice = getNewInputDevice(activeDesc);
3381 // Force new input selection if the new device can not be reached via current input
3382 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3383 setInputDevice(activeDesc->mIoHandle, newDevice);
3384 } else {
3385 closeInput(activeDesc->mIoHandle);
3386 }
3387 }
3388}
3389
jiabin0a488932020-08-07 17:32:40 -07003390status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3391 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003392{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003393 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003394
jiabin0a488932020-08-07 17:32:40 -07003395 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003396 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003397 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3398 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003399 return status;
3400 }
3401
3402 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003403
3404 bool forceVolumeReeval = false;
3405 // FIXME: workaround for truncated touch sounds
3406 // to be removed when the problem is handled by system UI
3407 uint32_t delayMs = 0;
3408 if (strategy == mCommunnicationStrategy) {
3409 forceVolumeReeval = true;
3410 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3411 updateInputRouting();
3412 }
3413 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003414
3415 return NO_ERROR;
3416}
3417
jiabin0a488932020-08-07 17:32:40 -07003418status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3419 device_role_t role,
3420 AudioDeviceTypeAddrVector &devices) {
3421 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003422}
3423
Jiabin Huang3b98d322020-09-03 17:54:16 +00003424status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3425 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3426 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3427 dumpAudioDeviceTypeAddrVector(devices).c_str());
3428
Mikhail Naganov55773032020-10-01 15:08:13 -07003429 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003430 return BAD_VALUE;
3431 }
3432 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3433 ALOGW_IF(status != NO_ERROR,
3434 "Engine could not set preferred devices %s for audio source %d role %d",
3435 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3436
3437 return status;
3438}
3439
3440status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3441 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3442 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3443 dumpAudioDeviceTypeAddrVector(devices).c_str());
3444
Mikhail Naganov55773032020-10-01 15:08:13 -07003445 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003446 return BAD_VALUE;
3447 }
3448 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3449 ALOGW_IF(status != NO_ERROR,
3450 "Engine could not add preferred devices %s for audio source %d role %d",
3451 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3452
Eric Laurent2517af32020-11-25 15:31:27 +01003453 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003454 return status;
3455}
3456
3457status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3458 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3459{
3460 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3461 dumpAudioDeviceTypeAddrVector(devices).c_str());
3462
Mikhail Naganov55773032020-10-01 15:08:13 -07003463 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003464 return BAD_VALUE;
3465 }
3466
3467 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3468 audioSource, role, devices);
3469 ALOGW_IF(status != NO_ERROR,
3470 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3471
Eric Laurent2517af32020-11-25 15:31:27 +01003472 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003473 return status;
3474}
3475
3476status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3477 device_role_t role) {
3478 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3479
3480 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3481 ALOGW_IF(status != NO_ERROR,
3482 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3483
Eric Laurent2517af32020-11-25 15:31:27 +01003484 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003485 return status;
3486}
3487
3488status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3489 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3490 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3491}
3492
Oscar Azucena90e77632019-11-27 17:12:28 -08003493status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003494 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003495 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003496 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3497 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003498 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003499 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3500 if (status != NO_ERROR) {
3501 ALOGE("%s() could not set device affinity for userId %d",
3502 __FUNCTION__, userId);
3503 return status;
3504 }
3505
3506 // reevaluate outputs for all devices
3507 checkForDeviceAndOutputChanges();
3508 updateCallAndOutputRouting();
3509
3510 return NO_ERROR;
3511}
3512
3513status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003514 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003515 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3516 if (status != NO_ERROR) {
3517 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3518 __FUNCTION__, userId);
3519 return status;
3520 }
3521
3522 // reevaluate outputs for all devices
3523 checkForDeviceAndOutputChanges();
3524 updateCallAndOutputRouting();
3525
3526 return NO_ERROR;
3527}
3528
Andy Hungc29d82b2018-10-05 12:23:17 -07003529void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003530{
Andy Hungc29d82b2018-10-05 12:23:17 -07003531 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3532 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003533 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003534 std::string stateLiteral;
3535 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003536 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003537 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3538 "communications", "media", "record", "dock", "system",
3539 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3540 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3541 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003542 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3543 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3544 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3545 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3546 dst->append(" (MANUAL: ");
3547 dumpManualSurroundFormats(dst);
3548 dst->append(")");
3549 }
3550 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003551 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003552 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3553 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003554 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003555 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003556
Andy Hungc29d82b2018-10-05 12:23:17 -07003557 mAvailableOutputDevices.dump(dst, String8("Available output"));
3558 mAvailableInputDevices.dump(dst, String8("Available input"));
3559 mHwModulesAll.dump(dst);
3560 mOutputs.dump(dst);
3561 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003562 mEffects.dump(dst);
3563 mAudioPatches.dump(dst);
3564 mPolicyMixes.dump(dst);
3565 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003566
Kevin Rocardb99cc752019-03-21 20:52:24 -07003567 dst->appendFormat(" AllowedCapturePolicies:\n");
3568 for (auto& policy : mAllowedCapturePolicies) {
3569 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3570 }
3571
François Gaffiec005e562018-11-06 15:04:49 +01003572 dst->appendFormat("\nPolicy Engine dump:\n");
3573 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003574}
3575
3576status_t AudioPolicyManager::dump(int fd)
3577{
3578 String8 result;
3579 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003580 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003581 return NO_ERROR;
3582}
3583
Kevin Rocardb99cc752019-03-21 20:52:24 -07003584status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3585{
3586 mAllowedCapturePolicies[uid] = capturePolicy;
3587 return NO_ERROR;
3588}
3589
Eric Laurente552edb2014-03-10 17:42:56 -07003590// This function checks for the parameters which can be offloaded.
3591// This can be enhanced depending on the capability of the DSP and policy
3592// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003593audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003594{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003595 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003596 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003597 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003598 offloadInfo.format,
3599 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3600 offloadInfo.has_video);
3601
Andy Hung2ddee192015-12-18 17:34:44 -08003602 if (mMasterMono) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003603 return AUDIO_OFFLOAD_NOT_SUPPORTED; // no offloading if mono is set.
Andy Hung2ddee192015-12-18 17:34:44 -08003604 }
3605
Eric Laurente552edb2014-03-10 17:42:56 -07003606 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003607 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003608 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3609 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003610 }
3611
3612 // Check if stream type is music, then only allow offload as of now.
3613 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3614 {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003615 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3616 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003617 }
3618
3619 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003620 const bool allowOffloadWithVideo =
3621 property_get_bool("audio.offload.video", false /* default_value */);
3622 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003623 ALOGV("%s: has_video == true, returning false", __func__);
3624 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003625 }
3626
3627 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003628 const int min_duration_secs = property_get_int32(
3629 "audio.offload.min.duration.secs", -1 /* default_value */);
3630 if (min_duration_secs >= 0) {
3631 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003632 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3633 __func__, min_duration_secs);
3634 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003635 }
3636 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003637 ALOGV("%s: Offload denied by duration < default min(=%u)",
3638 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3639 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003640 }
3641
3642 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3643 // creating an offloaded track and tearing it down immediately after start when audioflinger
3644 // detects there is an active non offloadable effect.
3645 // FIXME: We should check the audio session here but we do not have it in this context.
3646 // This may prevent offloading in rare situations where effects are left active by apps
3647 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003648 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003649 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003650 }
3651
3652 // See if there is a profile to support this.
3653 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003654 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003655 offloadInfo.sample_rate,
3656 offloadInfo.format,
3657 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003658 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3659 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003660 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3661 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3662 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003663 if (profile == nullptr) {
3664 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3665 }
3666 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3667 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3668 }
3669 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003670}
3671
Michael Chana94fbb22018-04-24 14:31:19 +10003672bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3673 const audio_attributes_t& attributes) {
3674 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003675 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003676 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003677 config.sample_rate,
3678 config.format,
3679 config.channel_mask,
3680 output_flags,
3681 true /* directOnly */);
3682 ALOGV("%s() profile %sfound with name: %s, "
3683 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3684 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003685 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003686 config.sample_rate, config.format, config.channel_mask, output_flags);
3687 return (profile != 0);
3688}
3689
Eric Laurent6a94d692014-05-20 11:18:06 -07003690status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3691 audio_port_type_t type,
3692 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003693 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003694 unsigned int *generation)
3695{
jiabin19cdba52020-11-24 11:28:58 -08003696 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3697 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003698 return BAD_VALUE;
3699 }
3700 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003701 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003702 *num_ports = 0;
3703 }
3704
3705 size_t portsWritten = 0;
3706 size_t portsMax = *num_ports;
3707 *num_ports = 0;
3708 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003709 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3710 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003711 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003712 for (const auto& dev : mAvailableOutputDevices) {
3713 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003714 continue;
3715 }
3716 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003717 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003718 }
3719 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003720 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003721 }
3722 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003723 for (const auto& dev : mAvailableInputDevices) {
3724 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003725 continue;
3726 }
3727 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003728 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003729 }
3730 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003731 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003732 }
3733 }
3734 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3735 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3736 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3737 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3738 }
3739 *num_ports += mInputs.size();
3740 }
3741 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003742 size_t numOutputs = 0;
3743 for (size_t i = 0; i < mOutputs.size(); i++) {
3744 if (!mOutputs[i]->isDuplicated()) {
3745 numOutputs++;
3746 if (portsWritten < portsMax) {
3747 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3748 }
3749 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003750 }
Eric Laurent84c70242014-06-23 08:46:27 -07003751 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003752 }
3753 }
3754 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003755 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003756 return NO_ERROR;
3757}
3758
jiabin19cdba52020-11-24 11:28:58 -08003759status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003760{
Eric Laurent99fcae42018-05-17 16:59:18 -07003761 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3762 return BAD_VALUE;
3763 }
3764 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3765 if (dev != 0) {
3766 dev->toAudioPort(port);
3767 return NO_ERROR;
3768 }
3769 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3770 if (dev != 0) {
3771 dev->toAudioPort(port);
3772 return NO_ERROR;
3773 }
3774 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3775 if (out != 0) {
3776 out->toAudioPort(port);
3777 return NO_ERROR;
3778 }
3779 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3780 if (in != 0) {
3781 in->toAudioPort(port);
3782 return NO_ERROR;
3783 }
3784 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003785}
3786
François Gaffieafd4cea2019-11-18 15:50:22 +01003787status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3788 audio_patch_handle_t *handle,
3789 uid_t uid, uint32_t delayMs,
3790 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003791{
François Gaffieafd4cea2019-11-18 15:50:22 +01003792 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003793 if (handle == NULL || patch == NULL) {
3794 return BAD_VALUE;
3795 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003796 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003797
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003798 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003799 return BAD_VALUE;
3800 }
3801 // only one source per audio patch supported for now
3802 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003803 return INVALID_OPERATION;
3804 }
Eric Laurent874c42872014-08-08 15:13:39 -07003805
3806 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003807 return INVALID_OPERATION;
3808 }
Eric Laurent874c42872014-08-08 15:13:39 -07003809 for (size_t i = 0; i < patch->num_sinks; i++) {
3810 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3811 return INVALID_OPERATION;
3812 }
3813 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003814
3815 sp<AudioPatch> patchDesc;
3816 ssize_t index = mAudioPatches.indexOfKey(*handle);
3817
François Gaffieafd4cea2019-11-18 15:50:22 +01003818 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3819 patch->sources[0].role,
3820 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003821#if LOG_NDEBUG == 0
3822 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003823 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3824 patch->sinks[i].role,
3825 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003826 }
3827#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003828
3829 if (index >= 0) {
3830 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003831 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3832 __func__, mUidCached, patchDesc->getUid(), uid);
3833 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003834 return INVALID_OPERATION;
3835 }
3836 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003837 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003838 }
3839
3840 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003841 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003842 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003843 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003844 return BAD_VALUE;
3845 }
Eric Laurent84c70242014-06-23 08:46:27 -07003846 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3847 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003848 if (patchDesc != 0) {
3849 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003850 ALOGV("%s source id differs for patch current id %d new id %d",
3851 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003852 return BAD_VALUE;
3853 }
3854 }
Eric Laurent874c42872014-08-08 15:13:39 -07003855 DeviceVector devices;
3856 for (size_t i = 0; i < patch->num_sinks; i++) {
3857 // Only support mix to devices connection
3858 // TODO add support for mix to mix connection
3859 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003860 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003861 return INVALID_OPERATION;
3862 }
3863 sp<DeviceDescriptor> devDesc =
3864 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3865 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003866 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003867 return BAD_VALUE;
3868 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003869
François Gaffie11d30102018-11-02 16:09:09 +01003870 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003871 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003872 NULL, // updatedSamplingRate
3873 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003874 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003875 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003876 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003877 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003878 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003879 return INVALID_OPERATION;
3880 }
3881 devices.add(devDesc);
3882 }
3883 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003884 return INVALID_OPERATION;
3885 }
Eric Laurent874c42872014-08-08 15:13:39 -07003886
Eric Laurent6a94d692014-05-20 11:18:06 -07003887 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003888 ALOGV("%s setting device %s on output %d",
3889 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003890 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003891 index = mAudioPatches.indexOfKey(*handle);
3892 if (index >= 0) {
3893 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003894 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003895 }
3896 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003897 patchDesc->setUid(uid);
3898 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003899 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003900 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003901 return INVALID_OPERATION;
3902 }
3903 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3904 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3905 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003906 // only one sink supported when connecting an input device to a mix
3907 if (patch->num_sinks > 1) {
3908 return INVALID_OPERATION;
3909 }
François Gaffie53615e22015-03-19 09:24:12 +01003910 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003911 if (inputDesc == NULL) {
3912 return BAD_VALUE;
3913 }
3914 if (patchDesc != 0) {
3915 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3916 return BAD_VALUE;
3917 }
3918 }
François Gaffie11d30102018-11-02 16:09:09 +01003919 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003920 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003921 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003922 return BAD_VALUE;
3923 }
3924
François Gaffie11d30102018-11-02 16:09:09 +01003925 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003926 patch->sinks[0].sample_rate,
3927 NULL, /*updatedSampleRate*/
3928 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003929 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003930 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003931 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003932 // FIXME for the parameter type,
3933 // and the NONE
3934 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003935 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003936 return INVALID_OPERATION;
3937 }
3938 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003939 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003940 device->toString().c_str(), inputDesc->mIoHandle);
3941 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003942 index = mAudioPatches.indexOfKey(*handle);
3943 if (index >= 0) {
3944 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003945 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003946 }
3947 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003948 patchDesc->setUid(uid);
3949 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003950 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003951 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003952 return INVALID_OPERATION;
3953 }
3954 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3955 // device to device connection
3956 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003957 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003958 return BAD_VALUE;
3959 }
3960 }
François Gaffie11d30102018-11-02 16:09:09 +01003961 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003962 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003963 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003964 return BAD_VALUE;
3965 }
Eric Laurent874c42872014-08-08 15:13:39 -07003966
Eric Laurent6a94d692014-05-20 11:18:06 -07003967 //update source and sink with our own data as the data passed in the patch may
3968 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01003969 PatchBuilder patchBuilder;
3970 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11003971
3972 // if first sink is to MSD, establish single MSD patch
3973 if (getMsdAudioOutDevices().contains(
3974 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
3975 ALOGV("%s patching to MSD", __FUNCTION__);
3976 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
3977 goto installPatch;
3978 }
3979
François Gaffieafd4cea2019-11-18 15:50:22 +01003980 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
3981 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07003982
Eric Laurent874c42872014-08-08 15:13:39 -07003983 for (size_t i = 0; i < patch->num_sinks; i++) {
3984 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003985 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003986 return INVALID_OPERATION;
3987 }
François Gaffie11d30102018-11-02 16:09:09 +01003988 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003989 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003990 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003991 return BAD_VALUE;
3992 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003993 audio_port_config sinkPortConfig = {};
3994 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
3995 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003996
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02003997 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
3998 // volume management purpose (tracking activity)
3999 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4000 // in config XML to reach the sink so that is can be declared as available.
4001 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4002 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4003 if (sourceDesc != nullptr) {
4004 // take care of dynamic routing for SwOutput selection,
4005 audio_attributes_t attributes = sourceDesc->attributes();
4006 audio_stream_type_t stream = sourceDesc->stream();
4007 audio_attributes_t resultAttr;
4008 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4009 config.sample_rate = sourceDesc->config().sample_rate;
4010 config.channel_mask = sourceDesc->config().channel_mask;
4011 config.format = sourceDesc->config().format;
4012 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4013 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4014 bool isRequestedDeviceForExclusiveUse = false;
4015 output_type_t outputType;
4016 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4017 &stream, sourceDesc->uid(), &config, &flags,
4018 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4019 nullptr, &outputType);
4020 if (output == AUDIO_IO_HANDLE_NONE) {
4021 ALOGV("%s no output for device %s",
4022 __FUNCTION__, sinkDevice->toString().c_str());
4023 return INVALID_OPERATION;
4024 }
4025 outputDesc = mOutputs.valueFor(output);
4026 if (outputDesc->isDuplicated()) {
4027 ALOGE("%s output is duplicated", __func__);
4028 return INVALID_OPERATION;
4029 }
4030 sourceDesc->setSwOutput(outputDesc);
4031 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004032 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004033 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004034 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004035 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01004036 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
4037 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004038 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4039 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004040 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
4041 (sourceDesc != nullptr &&
4042 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004043 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004044 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004045 return INVALID_OPERATION;
4046 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004047 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004048 SortedVector<audio_io_handle_t> outputs =
4049 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4050 // if the sink device is reachable via an opened output stream, request to
4051 // go via this output stream by adding a second source to the patch
4052 // description
4053 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004054 if (output != AUDIO_IO_HANDLE_NONE) {
4055 outputDesc = mOutputs.valueFor(output);
4056 if (outputDesc->isDuplicated()) {
4057 ALOGV("%s output for device %s is duplicated",
4058 __FUNCTION__, sinkDevice->toString().c_str());
4059 return INVALID_OPERATION;
4060 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004061 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004062 }
4063 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004064 audio_port_config srcMixPortConfig = {};
4065 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
François Gaffieafd4cea2019-11-18 15:50:22 +01004066 // for volume control, we may need a valid stream
4067 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
4068 sourceDesc->stream() : AUDIO_STREAM_PATCH;
4069 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004070 }
Eric Laurent83b88082014-06-20 18:31:16 -07004071 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004072 }
4073 // TODO: check from routing capabilities in config file and other conflicting patches
4074
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004075installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004076 status_t status = installPatch(
4077 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004078 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004079 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004080 return INVALID_OPERATION;
4081 }
4082 } else {
4083 return BAD_VALUE;
4084 }
4085 } else {
4086 return BAD_VALUE;
4087 }
4088 return NO_ERROR;
4089}
4090
4091status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4092 uid_t uid)
4093{
4094 ALOGV("releaseAudioPatch() patch %d", handle);
4095
4096 ssize_t index = mAudioPatches.indexOfKey(handle);
4097
4098 if (index < 0) {
4099 return BAD_VALUE;
4100 }
4101 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004102 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4103 __func__, mUidCached, patchDesc->getUid(), uid);
4104 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004105 return INVALID_OPERATION;
4106 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004107 return releaseAudioPatchInternal(handle);
4108}
Eric Laurent6a94d692014-05-20 11:18:06 -07004109
François Gaffieafd4cea2019-11-18 15:50:22 +01004110status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4111 uint32_t delayMs)
4112{
4113 ALOGV("%s patch %d", __func__, handle);
4114 if (mAudioPatches.indexOfKey(handle) < 0) {
4115 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4116 return BAD_VALUE;
4117 }
4118 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004119 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004120 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004121 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004122 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004123 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004124 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004125 return BAD_VALUE;
4126 }
4127
François Gaffie11d30102018-11-02 16:09:09 +01004128 setOutputDevices(outputDesc,
4129 getNewOutputDevices(outputDesc, true /*fromCache*/),
4130 true,
4131 0,
4132 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004133 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4134 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004135 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004136 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004137 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004138 return BAD_VALUE;
4139 }
4140 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004141 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004142 true,
4143 NULL);
4144 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004145 status_t status =
4146 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4147 ALOGV("%s patch panel returned %d patchHandle %d",
4148 __func__, status, patchDesc->getAfHandle());
4149 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004150 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004151 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004152 // SW Bridge
4153 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4154 sp<SwAudioOutputDescriptor> outputDesc =
4155 mOutputs.getOutputFromId(patch->sources[1].id);
4156 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004157 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4158 // releaseOutput has already called closeOuput in case of direct output
4159 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004160 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004161 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4162 // force SwOutput patch removal as AF counter part patch has already gone.
4163 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4164 removeAudioPatch(outputDesc->getPatchHandle());
4165 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004166 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4167 setOutputDevices(outputDesc,
4168 getNewOutputDevices(outputDesc, true /*fromCache*/),
4169 true, /*force*/
4170 0,
4171 NULL);
4172 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004173 } else {
4174 return BAD_VALUE;
4175 }
4176 } else {
4177 return BAD_VALUE;
4178 }
4179 return NO_ERROR;
4180}
4181
4182status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4183 struct audio_patch *patches,
4184 unsigned int *generation)
4185{
François Gaffie53615e22015-03-19 09:24:12 +01004186 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004187 return BAD_VALUE;
4188 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004189 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004190 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004191}
4192
Eric Laurente1715a42014-05-20 11:30:42 -07004193status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004194{
Eric Laurente1715a42014-05-20 11:30:42 -07004195 ALOGV("setAudioPortConfig()");
4196
4197 if (config == NULL) {
4198 return BAD_VALUE;
4199 }
4200 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4201 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004202 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4203 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004204 }
4205
Eric Laurenta121f902014-06-03 13:32:54 -07004206 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004207 if (config->type == AUDIO_PORT_TYPE_MIX) {
4208 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004209 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004210 if (outputDesc == NULL) {
4211 return BAD_VALUE;
4212 }
Eric Laurent84c70242014-06-23 08:46:27 -07004213 ALOG_ASSERT(!outputDesc->isDuplicated(),
4214 "setAudioPortConfig() called on duplicated output %d",
4215 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004216 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004217 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004218 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004219 if (inputDesc == NULL) {
4220 return BAD_VALUE;
4221 }
Eric Laurenta121f902014-06-03 13:32:54 -07004222 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004223 } else {
4224 return BAD_VALUE;
4225 }
4226 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4227 sp<DeviceDescriptor> deviceDesc;
4228 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4229 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4230 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4231 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4232 } else {
4233 return BAD_VALUE;
4234 }
4235 if (deviceDesc == NULL) {
4236 return BAD_VALUE;
4237 }
Eric Laurenta121f902014-06-03 13:32:54 -07004238 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004239 } else {
4240 return BAD_VALUE;
4241 }
4242
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004243 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004244 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4245 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004246 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004247 audioPortConfig->toAudioPortConfig(&newConfig, config);
4248 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004249 }
Eric Laurenta121f902014-06-03 13:32:54 -07004250 if (status != NO_ERROR) {
4251 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004252 }
Eric Laurente1715a42014-05-20 11:30:42 -07004253
4254 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004255}
4256
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004257void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4258{
Eric Laurentd60560a2015-04-10 11:31:20 -07004259 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004260 clearAudioPatches(uid);
4261 clearSessionRoutes(uid);
4262}
4263
Eric Laurent6a94d692014-05-20 11:18:06 -07004264void AudioPolicyManager::clearAudioPatches(uid_t uid)
4265{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004266 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004267 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004268 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004269 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004270 }
4271 }
4272}
4273
François Gaffiec005e562018-11-06 15:04:49 +01004274void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004275{
François Gaffiec005e562018-11-06 15:04:49 +01004276 // Take the first attributes following the product strategy as it is used to retrieve the routed
4277 // device. All attributes wihin a strategy follows the same "routing strategy"
4278 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4279 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004280 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004281 for (size_t j = 0; j < mOutputs.size(); j++) {
4282 if (mOutputs.keyAt(j) == ouptutToSkip) {
4283 continue;
4284 }
4285 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004286 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004287 continue;
4288 }
4289 // If the default device for this strategy is on another output mix,
4290 // invalidate all tracks in this strategy to force re connection.
4291 // Otherwise select new device on the output mix.
4292 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004293 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4294 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004295 }
4296 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004297 setOutputDevices(
4298 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004299 }
4300 }
4301}
4302
4303void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4304{
4305 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004306 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004307 for (size_t i = 0; i < mOutputs.size(); i++) {
4308 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004309 for (const auto& client : outputDesc->getClientIterable()) {
4310 if (client->hasPreferredDevice() && client->uid() == uid) {
4311 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004312 auto clientStrategy = client->strategy();
4313 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4314 end(affectedStrategies)) {
4315 continue;
4316 }
4317 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004318 }
4319 }
4320 }
4321 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004322 for (const auto& strategy : affectedStrategies) {
4323 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004324 }
4325
4326 // remove input routes associated with this uid
4327 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004328 for (size_t i = 0; i < mInputs.size(); i++) {
4329 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004330 for (const auto& client : inputDesc->getClientIterable()) {
4331 if (client->hasPreferredDevice() && client->uid() == uid) {
4332 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4333 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004334 }
4335 }
4336 }
4337 // reroute inputs if necessary
4338 SortedVector<audio_io_handle_t> inputsToClose;
4339 for (size_t i = 0; i < mInputs.size(); i++) {
4340 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004341 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004342 inputsToClose.add(inputDesc->mIoHandle);
4343 }
4344 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004345 for (const auto& input : inputsToClose) {
4346 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004347 }
4348}
4349
Eric Laurentd60560a2015-04-10 11:31:20 -07004350void AudioPolicyManager::clearAudioSources(uid_t uid)
4351{
4352 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004353 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4354 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004355 stopAudioSource(mAudioSources.keyAt(i));
4356 }
4357 }
4358}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004359
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004360status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4361 audio_io_handle_t *ioHandle,
4362 audio_devices_t *device)
4363{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004364 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4365 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004366 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004367 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004368
François Gaffiedf372692015-03-19 10:43:27 +01004369 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004370}
4371
Eric Laurentd60560a2015-04-10 11:31:20 -07004372status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004373 const audio_attributes_t *attributes,
4374 audio_port_handle_t *portId,
4375 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004376{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004377 ALOGV("%s", __FUNCTION__);
4378 *portId = AUDIO_PORT_HANDLE_NONE;
4379
4380 if (source == NULL || attributes == NULL || portId == NULL) {
4381 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4382 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004383 return BAD_VALUE;
4384 }
4385
Eric Laurentd60560a2015-04-10 11:31:20 -07004386 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4387 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004388 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4389 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004390 return INVALID_OPERATION;
4391 }
4392
François Gaffie11d30102018-11-02 16:09:09 +01004393 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004394 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004395 String8(source->ext.device.address),
4396 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004397 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004398 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004399 return BAD_VALUE;
4400 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004401
jiabin4ef93452019-09-10 14:29:54 -07004402 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004403
François Gaffieaaac0fd2018-11-22 17:56:39 +01004404 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004405 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004406 mEngine->getStreamTypeForAttributes(*attributes),
4407 mEngine->getProductStrategyForAttributes(*attributes),
4408 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004409
4410 status_t status = connectAudioSource(sourceDesc);
4411 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004412 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004413 }
4414 return status;
4415}
4416
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004417status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004418{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004419 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004420
4421 // make sure we only have one patch per source.
4422 disconnectAudioSource(sourceDesc);
4423
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004424 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004425 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4426 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4427 sourceDesc->srcDevice()->type(),
4428 String8(sourceDesc->srcDevice()->address().c_str()),
4429 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004430 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004431 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004432 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004433 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004434 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4435 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4436 return INVALID_OPERATION;
4437 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004438 PatchBuilder patchBuilder;
4439 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4440 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4441 status_t status =
4442 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4443 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4444 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4445 return INVALID_OPERATION;
4446 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004447 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004448 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4449 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4450 if (swOutput != 0) {
4451 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004452 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004453 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004454 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004455 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004456 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004457 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004458 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004459 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004460 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004461 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004462 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004463 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4464 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004465 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004466 if (delayMs != 0) {
4467 usleep(delayMs * 1000);
4468 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004469 } else {
4470 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4471 if (hwOutputDesc != 0) {
4472 // create Hwoutput and add to mHwOutputs
4473 } else {
4474 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4475 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004476 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004477 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004478
4479FailureSourceActive:
4480 swOutput->stop();
4481 releaseOutput(sourceDesc->portId());
4482FailureSourceAdded:
4483 sourceDesc->setSwOutput(nullptr);
4484FailureReleasePatch:
4485 releaseAudioPatchInternal(handle);
4486 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004487}
4488
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004489status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004490{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004491 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4492 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004493 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004494 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004495 return BAD_VALUE;
4496 }
4497 status_t status = disconnectAudioSource(sourceDesc);
4498
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004499 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004500 return status;
4501}
4502
Andy Hung2ddee192015-12-18 17:34:44 -08004503status_t AudioPolicyManager::setMasterMono(bool mono)
4504{
4505 if (mMasterMono == mono) {
4506 return NO_ERROR;
4507 }
4508 mMasterMono = mono;
4509 // if enabling mono we close all offloaded devices, which will invalidate the
4510 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4511 // for recreating the new AudioTrack as non-offloaded PCM.
4512 //
4513 // If disabling mono, we leave all tracks as is: we don't know which clients
4514 // and tracks are able to be recreated as offloaded. The next "song" should
4515 // play back offloaded.
4516 if (mMasterMono) {
4517 Vector<audio_io_handle_t> offloaded;
4518 for (size_t i = 0; i < mOutputs.size(); ++i) {
4519 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4520 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4521 offloaded.push(desc->mIoHandle);
4522 }
4523 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004524 for (const auto& handle : offloaded) {
4525 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004526 }
4527 }
4528 // update master mono for all remaining outputs
4529 for (size_t i = 0; i < mOutputs.size(); ++i) {
4530 updateMono(mOutputs.keyAt(i));
4531 }
4532 return NO_ERROR;
4533}
4534
4535status_t AudioPolicyManager::getMasterMono(bool *mono)
4536{
4537 *mono = mMasterMono;
4538 return NO_ERROR;
4539}
4540
Eric Laurentac9cef52017-06-09 15:46:26 -07004541float AudioPolicyManager::getStreamVolumeDB(
4542 audio_stream_type_t stream, int index, audio_devices_t device)
4543{
jiabin9a3361e2019-10-01 09:38:30 -07004544 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004545}
4546
jiabin81772902018-04-02 17:52:27 -07004547status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4548 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004549 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004550{
Kriti Dang6537def2021-03-02 13:46:59 +01004551 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4552 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004553 return BAD_VALUE;
4554 }
Kriti Dang6537def2021-03-02 13:46:59 +01004555 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4556 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004557
4558 size_t formatsWritten = 0;
4559 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004560
Kriti Dang6537def2021-03-02 13:46:59 +01004561 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004562 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4563 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004564 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07004565 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01004566 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004567 bool formatEnabled = true;
4568 switch (forceUse) {
4569 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01004570 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004571 break;
4572 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4573 formatEnabled = false;
4574 break;
4575 default: // AUTO or ALWAYS => true
4576 break;
jiabin81772902018-04-02 17:52:27 -07004577 }
4578 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4579 }
jiabin81772902018-04-02 17:52:27 -07004580 }
4581 return NO_ERROR;
4582}
4583
Kriti Dang6537def2021-03-02 13:46:59 +01004584status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
4585 audio_format_t *surroundFormats) {
4586 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
4587 return BAD_VALUE;
4588 }
4589 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
4590 __func__, *numSurroundFormats, surroundFormats);
4591
4592 size_t formatsWritten = 0;
4593 size_t formatsMax = *numSurroundFormats;
4594 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4595
4596 // Return formats from all device profiles that have already been resolved by
4597 // checkOutputsForDevice().
4598 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4599 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4600 audio_devices_t deviceType = device->type();
4601 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4602 // returns formats reported by HDMI devices.
4603 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4604 continue;
4605 }
4606 // Formats reported by sink devices
4607 std::unordered_set<audio_format_t> formatset;
4608 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4609 formatset.insert(it->second.begin(), it->second.end());
4610 }
4611
4612 // Formats hard-coded in the in policy configuration file (if any).
4613 FormatVector encodedFormats = device->encodedFormats();
4614 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4615 // Filter the formats which are supported by the vendor hardware.
4616 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4617 if (mConfig.getSurroundFormats().count(*it) != 0) {
4618 formats.insert(*it);
4619 } else {
4620 for (const auto& pair : mConfig.getSurroundFormats()) {
4621 if (pair.second.count(*it) != 0) {
4622 formats.insert(pair.first);
4623 break;
4624 }
4625 }
4626 }
4627 }
4628 }
4629 *numSurroundFormats = formats.size();
4630 for (const auto& format: formats) {
4631 if (formatsWritten < formatsMax) {
4632 surroundFormats[formatsWritten++] = format;
4633 }
4634 }
4635 return NO_ERROR;
4636}
4637
jiabin81772902018-04-02 17:52:27 -07004638status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4639{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004640 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004641 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4642 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004643 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004644 return BAD_VALUE;
4645 }
4646
Mikhail Naganov100f0122018-11-29 11:22:16 -08004647 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4648 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004649 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004650 return INVALID_OPERATION;
4651 }
4652
Mikhail Naganov100f0122018-11-29 11:22:16 -08004653 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004654 return NO_ERROR;
4655 }
4656
Mikhail Naganov100f0122018-11-29 11:22:16 -08004657 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004658 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004659 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004660 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004661 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004662 }
4663 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004664 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004665 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004666 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004667 }
4668 }
4669
4670 sp<SwAudioOutputDescriptor> outputDesc;
4671 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004672 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4673 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004674 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4675 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004676 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004677 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004678 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4679 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4680 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004681 name.c_str(),
4682 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004683 if (status != NO_ERROR) {
4684 continue;
4685 }
4686 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4687 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4688 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004689 name.c_str(),
4690 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004691 profileUpdated |= (status == NO_ERROR);
4692 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004693 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004694 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004695 AUDIO_DEVICE_IN_HDMI);
4696 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4697 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004698 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004699 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004700 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4701 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4702 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004703 name.c_str(),
4704 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004705 if (status != NO_ERROR) {
4706 continue;
4707 }
4708 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4709 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4710 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004711 name.c_str(),
4712 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004713 profileUpdated |= (status == NO_ERROR);
4714 }
4715
jiabin81772902018-04-02 17:52:27 -07004716 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004717 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004718 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004719 }
4720
4721 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4722}
4723
Eric Laurent5ada82e2019-08-29 17:53:54 -07004724void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004725{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004726 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004727 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004728 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004729 }
4730}
4731
jiabin6012f912018-11-02 17:06:30 -07004732bool AudioPolicyManager::isHapticPlaybackSupported()
4733{
4734 for (const auto& hwModule : mHwModules) {
4735 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4736 for (const auto &outProfile : outputProfiles) {
4737 struct audio_port audioPort;
4738 outProfile->toAudioPort(&audioPort);
4739 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4740 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4741 return true;
4742 }
4743 }
4744 }
4745 }
4746 return false;
4747}
4748
Eric Laurent8340e672019-11-06 11:01:08 -08004749bool AudioPolicyManager::isCallScreenModeSupported()
4750{
4751 return getConfig().isCallScreenModeSupported();
4752}
4753
4754
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004755status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004756{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004757 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004758 if (!sourceDesc->isConnected()) {
4759 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
4760 return NO_ERROR;
4761 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004762 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4763 if (swOutput != 0) {
4764 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004765 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004766 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004767 }
jiabinbce0c1d2020-10-05 11:20:18 -07004768 if (releaseOutput(sourceDesc->portId())) {
4769 // The output descriptor is reopened to query dynamic profiles. In that case, there is
4770 // no need to release audio patch here but just return NO_ERROR.
4771 return NO_ERROR;
4772 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004773 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004774 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004775 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004776 // close Hwoutput and remove from mHwOutputs
4777 } else {
4778 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4779 }
4780 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004781 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
4782 sourceDesc->disconnect();
4783 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07004784}
4785
François Gaffiec005e562018-11-06 15:04:49 +01004786sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4787 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004788{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004789 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004790 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004791 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004792 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004793 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4794 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004795 source = sourceDesc;
4796 break;
4797 }
4798 }
4799 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004800}
4801
Eric Laurente552edb2014-03-10 17:42:56 -07004802// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004803// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004804// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004805uint32_t AudioPolicyManager::nextAudioPortGeneration()
4806{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004807 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004808}
4809
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004810static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07004811 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
4812 !audioPolicyXmlConfigFile.empty()) {
4813 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
4814 if (ret == NO_ERROR) {
4815 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08004816 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004817 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07004818 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004819 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004820}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004821
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004822AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4823 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004824 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004825 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004826 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004827 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004828 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004829 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004830 mAudioPortGeneration(1),
4831 mBeaconMuteRefCount(0),
4832 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004833 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004834 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004835 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004836 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004837{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004838}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004839
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004840AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4841 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4842{
4843 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004844}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004845
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004846void AudioPolicyManager::loadConfig() {
4847 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004848 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004849 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004850 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004851}
4852
4853status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07004854 {
4855 auto engLib = EngineLibrary::load(
4856 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
4857 if (!engLib) {
4858 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
4859 return NO_INIT;
4860 }
4861 mEngine = engLib->createEngine();
4862 if (mEngine == nullptr) {
4863 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
4864 return NO_INIT;
4865 }
François Gaffie2110e042015-03-24 08:41:51 +01004866 }
4867 mEngine->setObserver(this);
4868 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004869 if (status != NO_ERROR) {
4870 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4871 return status;
4872 }
François Gaffie2110e042015-03-24 08:41:51 +01004873
Eric Laurent1d69c872021-01-11 18:53:01 +01004874 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
4875 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
4876
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004877 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07004878 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004879 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01004880
Eric Laurent3a4311c2014-03-17 12:00:47 -07004881 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004882 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4883 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4884 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004885 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004886 }
jiabin9ff780e2018-03-19 18:19:52 -07004887 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07004888 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07004889 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004890 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004891 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004892 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004893 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004894 }
4895 }
4896 }
Eric Laurente552edb2014-03-10 17:42:56 -07004897
Francois Gaffiebce7cd42020-10-14 16:13:20 +02004898 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07004899
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004900 // Silence ALOGV statements
4901 property_set("log.tag." LOG_TAG, "D");
4902
Eric Laurente552edb2014-03-10 17:42:56 -07004903 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004904 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004905}
4906
Eric Laurente0720872014-03-11 09:30:41 -07004907AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004908{
Eric Laurente552edb2014-03-10 17:42:56 -07004909 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004910 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004911 }
4912 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004913 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004914 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004915 mAvailableOutputDevices.clear();
4916 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004917 mOutputs.clear();
4918 mInputs.clear();
4919 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004920 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004921 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004922}
4923
Eric Laurente0720872014-03-11 09:30:41 -07004924status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004925{
Eric Laurent87ffa392015-05-22 10:32:38 -07004926 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004927}
4928
Eric Laurente552edb2014-03-10 17:42:56 -07004929// ---
4930
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004931void AudioPolicyManager::onNewAudioModulesAvailable()
4932{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004933 DeviceVector newDevices;
4934 onNewAudioModulesAvailableInt(&newDevices);
4935 if (!newDevices.empty()) {
4936 nextAudioPortGeneration();
4937 mpClientInterface->onAudioPortListUpdate();
4938 }
4939}
4940
4941void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
4942{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004943 for (const auto& hwModule : mHwModulesAll) {
4944 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
4945 continue;
4946 }
4947 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
4948 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4949 ALOGW("could not open HW module %s", hwModule->getName());
4950 continue;
4951 }
4952 mHwModules.push_back(hwModule);
4953 // open all output streams needed to access attached devices
4954 // except for direct output streams that are only opened when they are actually
4955 // required by an app.
4956 // This also validates mAvailableOutputDevices list
4957 for (const auto& outProfile : hwModule->getOutputProfiles()) {
4958 if (!outProfile->canOpenNewIo()) {
4959 ALOGE("Invalid Output profile max open count %u for profile %s",
4960 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4961 continue;
4962 }
4963 if (!outProfile->hasSupportedDevices()) {
4964 ALOGW("Output profile contains no device on module %s", hwModule->getName());
4965 continue;
4966 }
4967 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
4968 mTtsOutputAvailable = true;
4969 }
4970
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004971 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4972 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
4973 sp<DeviceDescriptor> supportedDevice = 0;
4974 if (supportedDevices.contains(mDefaultOutputDevice)) {
4975 supportedDevice = mDefaultOutputDevice;
4976 } else {
4977 // choose first device present in profile's SupportedDevices also part of
4978 // mAvailableOutputDevices.
4979 if (availProfileDevices.isEmpty()) {
4980 continue;
4981 }
4982 supportedDevice = availProfileDevices.itemAt(0);
4983 }
4984 if (!mOutputDevicesAll.contains(supportedDevice)) {
4985 continue;
4986 }
4987 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4988 mpClientInterface);
4989 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4990 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4991 AUDIO_STREAM_DEFAULT,
4992 AUDIO_OUTPUT_FLAG_NONE, &output);
4993 if (status != NO_ERROR) {
4994 ALOGW("Cannot open output stream for devices %s on hw module %s",
4995 supportedDevice->toString().c_str(), hwModule->getName());
4996 continue;
4997 }
4998 for (const auto &device : availProfileDevices) {
4999 // give a valid ID to an attached device once confirmed it is reachable
5000 if (!device->isAttached()) {
5001 device->attach(hwModule);
5002 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005003 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005004 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005005 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5006 }
5007 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005008 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005009 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5010 mPrimaryOutput = outputDesc;
5011 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005012 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
5013 outputDesc->close();
5014 } else {
5015 addOutput(output, outputDesc);
5016 setOutputDevices(outputDesc,
5017 DeviceVector(supportedDevice),
5018 true,
5019 0,
5020 NULL);
5021 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005022 }
5023 // open input streams needed to access attached devices to validate
5024 // mAvailableInputDevices list
5025 for (const auto& inProfile : hwModule->getInputProfiles()) {
5026 if (!inProfile->canOpenNewIo()) {
5027 ALOGE("Invalid Input profile max open count %u for profile %s",
5028 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5029 continue;
5030 }
5031 if (!inProfile->hasSupportedDevices()) {
5032 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5033 continue;
5034 }
5035 // chose first device present in profile's SupportedDevices also part of
5036 // available input devices
5037 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5038 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5039 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005040 ALOGV("%s: Input device list is empty! for profile %s",
5041 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005042 continue;
5043 }
5044 sp<AudioInputDescriptor> inputDesc =
5045 new AudioInputDescriptor(inProfile, mpClientInterface);
5046
5047 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5048 status_t status = inputDesc->open(nullptr,
5049 availProfileDevices.itemAt(0),
5050 AUDIO_SOURCE_MIC,
5051 AUDIO_INPUT_FLAG_NONE,
5052 &input);
5053 if (status != NO_ERROR) {
5054 ALOGW("Cannot open input stream for device %s on hw module %s",
5055 availProfileDevices.toString().c_str(),
5056 hwModule->getName());
5057 continue;
5058 }
5059 for (const auto &device : availProfileDevices) {
5060 // give a valid ID to an attached device once confirmed it is reachable
5061 if (!device->isAttached()) {
5062 device->attach(hwModule);
5063 device->importAudioPortAndPickAudioProfile(inProfile, true);
5064 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005065 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005066 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5067 }
5068 }
5069 inputDesc->close();
5070 }
5071 }
5072}
5073
Eric Laurent98e38192018-02-15 18:31:53 -08005074void AudioPolicyManager::addOutput(audio_io_handle_t output,
5075 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005076{
Eric Laurent1c333e22014-05-20 10:48:17 -07005077 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005078 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005079 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005080 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005081 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005082}
5083
François Gaffie53615e22015-03-19 09:24:12 +01005084void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5085{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005086 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5087 ALOGV("%s: removing primary output", __func__);
5088 mPrimaryOutput = nullptr;
5089 }
François Gaffie53615e22015-03-19 09:24:12 +01005090 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005091 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005092}
5093
Eric Laurent98e38192018-02-15 18:31:53 -08005094void AudioPolicyManager::addInput(audio_io_handle_t input,
5095 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005096{
Eric Laurent1c333e22014-05-20 10:48:17 -07005097 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005098 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005099}
Eric Laurente552edb2014-03-10 17:42:56 -07005100
François Gaffie11d30102018-11-02 16:09:09 +01005101status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005102 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005103 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005104{
François Gaffie11d30102018-11-02 16:09:09 +01005105 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005106 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005107 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005108
François Gaffie11d30102018-11-02 16:09:09 +01005109 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005110 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005111 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005112 }
Eric Laurente552edb2014-03-10 17:42:56 -07005113
Eric Laurent3b73df72014-03-11 09:06:29 -07005114 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005115 // first call getAudioPort to get the supported attributes from the HAL
5116 struct audio_port_v7 port = {};
5117 device->toAudioPort(&port);
5118 status_t status = mpClientInterface->getAudioPort(&port);
5119 if (status == NO_ERROR) {
5120 device->importAudioPort(port);
5121 }
5122
5123 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005124 for (size_t i = 0; i < mOutputs.size(); i++) {
5125 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005126 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005127 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005128 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5129 mOutputs.keyAt(i), device->toString().c_str());
5130 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005131 }
5132 }
5133 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005134 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005135 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005136 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5137 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005138 if (profile->supportsDevice(device)) {
5139 profiles.add(profile);
5140 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5141 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005142 }
5143 }
5144 }
5145
Eric Laurent7b279bb2015-12-14 10:18:23 -08005146 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005147
Eric Laurente552edb2014-03-10 17:42:56 -07005148 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005149 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005150 return BAD_VALUE;
5151 }
5152
5153 // open outputs for matching profiles if needed. Direct outputs are also opened to
5154 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5155 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005156 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005157
5158 // nothing to do if one output is already opened for this profile
5159 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005160 for (j = 0; j < outputs.size(); j++) {
5161 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005162 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005163 // matching profile: save the sample rates, format and channel masks supported
5164 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005165 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005166 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005167 }
Eric Laurente552edb2014-03-10 17:42:56 -07005168 break;
5169 }
5170 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005171 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005172 continue;
5173 }
5174
Eric Laurent3974e3b2017-12-07 17:58:43 -08005175 if (!profile->canOpenNewIo()) {
5176 ALOGW("Max Output number %u already opened for this profile %s",
5177 profile->maxOpenCount, profile->getTagName().c_str());
5178 continue;
5179 }
5180
Eric Laurent83efe1c2017-07-09 16:51:08 -07005181 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005182 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005183 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5184 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005185 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005186 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005187 profiles.removeAt(profile_index);
5188 profile_index--;
5189 } else {
5190 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005191 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005192 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005193 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5194 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005195 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005196 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005197
François Gaffie11d30102018-11-02 16:09:09 +01005198 if (device_distinguishes_on_address(deviceType)) {
5199 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5200 device->toString().c_str());
5201 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5202 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005203 }
Eric Laurente552edb2014-03-10 17:42:56 -07005204 ALOGV("checkOutputsForDevice(): adding output %d", output);
5205 }
5206 }
5207
5208 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005209 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005210 return BAD_VALUE;
5211 }
Eric Laurentd4692962014-05-05 18:13:44 -07005212 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005213 // check if one opened output is not needed any more after disconnecting one device
5214 for (size_t i = 0; i < mOutputs.size(); i++) {
5215 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005216 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005217 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005218 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
jiabinbce0c1d2020-10-05 11:20:18 -07005219 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005220 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005221 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005222 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5223 mOutputs.keyAt(i));
5224 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005225 }
Eric Laurente552edb2014-03-10 17:42:56 -07005226 }
5227 }
Eric Laurentd4692962014-05-05 18:13:44 -07005228 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005229 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005230 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5231 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005232 if (!profile->supportsDevice(device)) {
5233 continue;
5234 }
5235 ALOGV("checkOutputsForDevice(): "
5236 "clearing direct output profile %zu on module %s",
5237 j, hwModule->getName());
5238 profile->clearAudioProfiles();
5239 if (!profile->hasDynamicAudioProfile()) {
5240 continue;
5241 }
5242 // When a device is disconnected, if there is an IOProfile that contains dynamic
5243 // profiles and supports the disconnected device, call getAudioPort to repopulate
5244 // the capabilities of the devices that is supported by the IOProfile.
5245 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5246 if (supportedDevice == device ||
5247 !mAvailableOutputDevices.contains(supportedDevice)) {
5248 continue;
5249 }
5250 struct audio_port_v7 port;
5251 supportedDevice->toAudioPort(&port);
5252 status_t status = mpClientInterface->getAudioPort(&port);
5253 if (status == NO_ERROR) {
5254 supportedDevice->importAudioPort(port);
5255 }
Eric Laurente552edb2014-03-10 17:42:56 -07005256 }
5257 }
5258 }
5259 }
5260 return NO_ERROR;
5261}
5262
François Gaffie11d30102018-11-02 16:09:09 +01005263status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005264 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005265{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005266 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005267
François Gaffie11d30102018-11-02 16:09:09 +01005268 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005269 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005270 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005271 }
5272
Eric Laurentd4692962014-05-05 18:13:44 -07005273 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005274 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005275 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005276 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005277 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005278 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005279 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005280 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005281
François Gaffie11d30102018-11-02 16:09:09 +01005282 if (profile->supportsDevice(device)) {
5283 profiles.add(profile);
5284 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5285 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005286 }
5287 }
5288 }
5289
Eric Laurent0dd51852019-04-19 18:18:58 -07005290 if (profiles.isEmpty()) {
5291 ALOGW("%s: No input profile available for device %s",
5292 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005293 return BAD_VALUE;
5294 }
5295
5296 // open inputs for matching profiles if needed. Direct inputs are also opened to
5297 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5298 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5299
Eric Laurent1c333e22014-05-20 10:48:17 -07005300 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005301
Eric Laurentd4692962014-05-05 18:13:44 -07005302 // nothing to do if one input is already opened for this profile
5303 size_t input_index;
5304 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5305 desc = mInputs.valueAt(input_index);
5306 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005307 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005308 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005309 }
Eric Laurentd4692962014-05-05 18:13:44 -07005310 break;
5311 }
5312 }
5313 if (input_index != mInputs.size()) {
5314 continue;
5315 }
5316
Eric Laurent3974e3b2017-12-07 17:58:43 -08005317 if (!profile->canOpenNewIo()) {
5318 ALOGW("Max Input number %u already opened for this profile %s",
5319 profile->maxOpenCount, profile->getTagName().c_str());
5320 continue;
5321 }
5322
Eric Laurentfe231122017-11-17 17:48:06 -08005323 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005324 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005325 status_t status = desc->open(nullptr,
5326 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005327 AUDIO_SOURCE_MIC,
5328 AUDIO_INPUT_FLAG_NONE,
5329 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005330
Eric Laurentcf2c0212014-07-25 16:20:43 -07005331 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005332 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005333 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005334 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005335 mpClientInterface->setParameters(input, String8(param));
5336 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005337 }
François Gaffie11d30102018-11-02 16:09:09 +01005338 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005339 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005340 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005341 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005342 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005343 }
5344
Eric Laurent0dd51852019-04-19 18:18:58 -07005345 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005346 addInput(input, desc);
5347 }
5348 } // endif input != 0
5349
Eric Laurentcf2c0212014-07-25 16:20:43 -07005350 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005351 ALOGW("%s could not open input for device %s", __func__,
5352 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005353 profiles.removeAt(profile_index);
5354 profile_index--;
5355 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005356 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005357 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005358 }
Eric Laurentd4692962014-05-05 18:13:44 -07005359 ALOGV("checkInputsForDevice(): adding input %d", input);
5360 }
5361 } // end scan profiles
5362
5363 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005364 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005365 return BAD_VALUE;
5366 }
5367 } else {
5368 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005369 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005370 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005371 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005372 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005373 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005374 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005375 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005376 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5377 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005378 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005379 }
5380 }
5381 }
5382 } // end disconnect
5383
5384 return NO_ERROR;
5385}
5386
5387
Eric Laurente0720872014-03-11 09:30:41 -07005388void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005389{
5390 ALOGV("closeOutput(%d)", output);
5391
François Gaffie1c878552018-11-22 16:53:21 +01005392 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5393 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005394 ALOGW("closeOutput() unknown output %d", output);
5395 return;
5396 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005397 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005398 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005399
Eric Laurente552edb2014-03-10 17:42:56 -07005400 // look for duplicated outputs connected to the output being removed.
5401 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005402 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5403 if (dupOutput->isDuplicated() &&
5404 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5405 sp<SwAudioOutputDescriptor> remainingOutput =
5406 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005407 // As all active tracks on duplicated output will be deleted,
5408 // and as they were also referenced on the other output, the reference
5409 // count for their stream type must be adjusted accordingly on
5410 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005411 const bool wasActive = remainingOutput->isActive();
5412 // Note: no-op on the closing output where all clients has already been set inactive
5413 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005414 // stop() will be a no op if the output is still active but is needed in case all
5415 // active streams refcounts where cleared above
5416 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005417 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005418 }
Eric Laurente552edb2014-03-10 17:42:56 -07005419 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5420 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5421
5422 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005423 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005424 }
5425 }
5426
Eric Laurent05b90f82014-08-27 15:32:29 -07005427 nextAudioPortGeneration();
5428
François Gaffie1c878552018-11-22 16:53:21 +01005429 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005430 if (index >= 0) {
5431 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005432 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5433 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005434 mAudioPatches.removeItemsAt(index);
5435 mpClientInterface->onAudioPatchListUpdate();
5436 }
5437
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005438 if (closingOutputWasActive) {
5439 closingOutput->stop();
5440 }
François Gaffie1c878552018-11-22 16:53:21 +01005441 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005442
François Gaffie53615e22015-03-19 09:24:12 +01005443 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005444 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005445
5446 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5447 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005448 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005449 bool directOutputOpen = false;
5450 for (size_t i = 0; i < mOutputs.size(); i++) {
5451 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5452 directOutputOpen = true;
5453 break;
5454 }
5455 }
5456 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11005457 ALOGV("no direct outputs open, reset MSD patches");
5458 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5459 // how output devices for patching are resolved. Avoid by caching and reusing the
5460 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5461 // devices to patch to. This may be complicated by the fact that devices may become
5462 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005463 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005464 }
5465 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005466}
5467
5468void AudioPolicyManager::closeInput(audio_io_handle_t input)
5469{
5470 ALOGV("closeInput(%d)", input);
5471
5472 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5473 if (inputDesc == NULL) {
5474 ALOGW("closeInput() unknown input %d", input);
5475 return;
5476 }
5477
Eric Laurent6a94d692014-05-20 11:18:06 -07005478 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005479
François Gaffie11d30102018-11-02 16:09:09 +01005480 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005481 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005482 if (index >= 0) {
5483 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005484 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5485 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005486 mAudioPatches.removeItemsAt(index);
5487 mpClientInterface->onAudioPatchListUpdate();
5488 }
5489
Eric Laurentfe231122017-11-17 17:48:06 -08005490 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005491 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005492
François Gaffie11d30102018-11-02 16:09:09 +01005493 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5494 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005495 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005496 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005497 }
Eric Laurente552edb2014-03-10 17:42:56 -07005498}
5499
François Gaffie11d30102018-11-02 16:09:09 +01005500SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5501 const DeviceVector &devices,
5502 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005503{
5504 SortedVector<audio_io_handle_t> outputs;
5505
François Gaffie11d30102018-11-02 16:09:09 +01005506 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005507 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005508 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005509 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005510 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005511 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005512 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005513 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005514 outputs.add(openOutputs.keyAt(i));
5515 }
5516 }
5517 return outputs;
5518}
5519
Mikhail Naganov37977152018-07-11 15:54:44 -07005520void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5521{
5522 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5523 // output is suspended before any tracks are moved to it
5524 checkA2dpSuspend();
5525 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005526 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005527 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005528 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005529 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11005530 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
5531 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
5532 // configuration changes will ultimately be rerouted correctly. We can still avoid
5533 // unnecessary rerouting by caching and reusing the arguments to
5534 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
5535 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005536 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005537 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07005538 // an event that changed routing likely occurred, inform upper layers
5539 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07005540}
5541
François Gaffiec005e562018-11-06 15:04:49 +01005542bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5543 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005544{
François Gaffiec005e562018-11-06 15:04:49 +01005545 return mEngine->getProductStrategyForAttributes(lAttr) ==
5546 mEngine->getProductStrategyForAttributes(rAttr);
5547}
5548
Francois Gaffieff1eb522020-05-06 18:37:04 +02005549void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
5550{
5551 for (size_t i = 0; i < mAudioSources.size(); i++) {
5552 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5553 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005554 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
5555 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02005556 connectAudioSource(sourceDesc);
5557 }
5558 }
5559}
5560
5561void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
5562{
5563 for (size_t i = 0; i < mAudioSources.size(); i++) {
5564 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5565 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
5566 && sourceDesc->swOutput().promote()->mIoHandle == output) {
5567 disconnectAudioSource(sourceDesc);
5568 }
5569 }
5570}
5571
François Gaffiec005e562018-11-06 15:04:49 +01005572void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5573{
5574 auto psId = mEngine->getProductStrategyForAttributes(attr);
5575
5576 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5577 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005578
François Gaffie11d30102018-11-02 16:09:09 +01005579 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5580 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005581
Eric Laurentc209fe42020-06-05 18:11:23 -07005582 uint32_t maxLatency = 0;
5583 bool invalidate = false;
5584 // take into account dynamic audio policies related changes: if a client is now associated
5585 // to a different policy mix than at creation time, invalidate corresponding stream
5586 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5587 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5588 if (desc->isDuplicated()) {
5589 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005590 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005591 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5592 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5593 continue;
5594 }
5595 sp<AudioPolicyMix> primaryMix;
5596 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5597 client->flags(), primaryMix, nullptr);
5598 if (status != OK) {
5599 continue;
5600 }
yucliuf4de36d2020-09-14 14:57:56 -07005601 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005602 invalidate = true;
5603 if (desc->isStrategyActive(psId)) {
5604 maxLatency = desc->latency();
5605 }
5606 break;
5607 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005608 }
5609 }
5610
Eric Laurentc209fe42020-06-05 18:11:23 -07005611 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005612 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5613 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005614 for (audio_io_handle_t srcOut : srcOutputs) {
5615 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005616 if (desc == nullptr) continue;
5617
5618 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005619 maxLatency = desc->latency();
5620 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005621
5622 if (invalidate) continue;
5623
5624 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005625 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005626 // a client on a non direct outputs has necessarily a linear PCM format
5627 // so we can call selectOutput() safely
5628 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5629 client->flags(),
5630 client->config().format,
5631 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07005632 client->config().sample_rate,
5633 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07005634 if (newOutput != srcOut) {
5635 invalidate = true;
5636 break;
5637 }
5638 } else {
5639 sp<IOProfile> profile = getProfileForOutput(newDevices,
5640 client->config().sample_rate,
5641 client->config().format,
5642 client->config().channel_mask,
5643 client->flags(),
5644 true /* directOnly */);
5645 if (profile != desc->mProfile) {
5646 invalidate = true;
5647 break;
5648 }
5649 }
5650 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005651 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005652
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005653 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005654 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005655 std::to_string(srcOutputs[0]).c_str(),
5656 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005657 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005658 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005659 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005660 if (desc == nullptr) continue;
5661
5662 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005663 setStrategyMute(psId, true, desc);
5664 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005665 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005666 }
François Gaffiec005e562018-11-06 15:04:49 +01005667 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005668 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005669 connectAudioSource(source);
5670 }
Eric Laurente552edb2014-03-10 17:42:56 -07005671 }
5672
François Gaffiec005e562018-11-06 15:04:49 +01005673 // Move effects associated to this stream from previous output to new output
5674 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005675 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005676 }
François Gaffiec005e562018-11-06 15:04:49 +01005677 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005678 if (invalidate) {
5679 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5680 mpClientInterface->invalidateStream(stream);
5681 }
Eric Laurente552edb2014-03-10 17:42:56 -07005682 }
5683 }
5684}
5685
Eric Laurente0720872014-03-11 09:30:41 -07005686void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005687{
François Gaffiec005e562018-11-06 15:04:49 +01005688 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5689 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5690 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02005691 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01005692 }
Eric Laurente552edb2014-03-10 17:42:56 -07005693}
5694
Kevin Rocard153f92d2018-12-18 18:33:28 -08005695void AudioPolicyManager::checkSecondaryOutputs() {
5696 std::set<audio_stream_type_t> streamsToInvalidate;
5697 for (size_t i = 0; i < mOutputs.size(); i++) {
5698 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5699 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005700 sp<AudioPolicyMix> primaryMix;
5701 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07005702 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07005703 client->flags(), primaryMix, &secondaryMixes);
5704 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5705 for (auto &secondaryMix : secondaryMixes) {
5706 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5707 if (outputDesc != nullptr &&
5708 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5709 secondaryDescs.push_back(outputDesc);
5710 }
5711 }
5712
Kevin Rocard94114a22019-04-01 19:38:23 -07005713 if (status != OK ||
5714 !std::equal(client->getSecondaryOutputs().begin(),
Kevin Rocard153f92d2018-12-18 18:33:28 -08005715 client->getSecondaryOutputs().end(),
5716 secondaryDescs.begin(), secondaryDescs.end())) {
5717 streamsToInvalidate.insert(client->stream());
5718 }
5719 }
5720 }
5721 for (audio_stream_type_t stream : streamsToInvalidate) {
5722 ALOGD("%s Invalidate stream %d due to secondary output change", __func__, stream);
5723 mpClientInterface->invalidateStream(stream);
5724 }
5725}
5726
Eric Laurent2517af32020-11-25 15:31:27 +01005727bool AudioPolicyManager::isScoRequestedForComm() const {
5728 AudioDeviceTypeAddrVector devices;
5729 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
5730 for (const auto &device : devices) {
5731 if (audio_is_bluetooth_out_sco_device(device.mType)) {
5732 return true;
5733 }
5734 }
5735 return false;
5736}
5737
Eric Laurente0720872014-03-11 09:30:41 -07005738void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005739{
François Gaffie53615e22015-03-19 09:24:12 +01005740 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005741 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005742 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005743 return;
5744 }
5745
Eric Laurent3a4311c2014-03-17 12:00:47 -07005746 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07005747 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
5748 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01005749 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07005750
5751 // if suspended, restore A2DP output if:
5752 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01005753 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07005754 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005755 //
Eric Laurentf732e072016-08-03 19:30:28 -07005756 // if not suspended, suspend A2DP output if:
5757 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01005758 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07005759 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005760 //
5761 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005762 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01005763 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07005764 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005765 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005766
5767 mpClientInterface->restoreOutput(a2dpOutput);
5768 mA2dpSuspended = false;
5769 }
5770 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005771 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01005772 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07005773 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005774 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005775
5776 mpClientInterface->suspendOutput(a2dpOutput);
5777 mA2dpSuspended = true;
5778 }
5779 }
5780}
5781
François Gaffie11d30102018-11-02 16:09:09 +01005782DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5783 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005784{
François Gaffie11d30102018-11-02 16:09:09 +01005785 DeviceVector devices;
5786
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005787 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005788 if (index >= 0) {
5789 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005790 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005791 ALOGV("%s device %s forced by patch %d", __func__,
5792 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5793 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005794 }
5795 }
5796
Dean Wheatley514b4312020-06-17 21:45:00 +10005797 // Do not retrieve engine device for outputs through MSD
5798 // TODO: support explicit routing requests by resetting MSD patch to engine device.
5799 if (outputDesc->devices() == getMsdAudioOutDevices()) {
5800 return outputDesc->devices();
5801 }
5802
Eric Laurent97ac8712018-07-27 18:59:02 -07005803 // Honor explicit routing requests only if no client using default routing is active on this
5804 // input: a specific app can not force routing for other apps by setting a preferred device.
5805 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005806 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005807 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005808 if (device != nullptr) {
5809 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07005810 }
5811
François Gaffiea807ef92018-11-05 10:44:33 +01005812 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5813 // of setForceUse / Default Bus device here
5814 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5815 if (device != nullptr) {
5816 return DeviceVector(device);
5817 }
5818
François Gaffiec005e562018-11-06 15:04:49 +01005819 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5820 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5821 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305822 auto hasStreamActive = [&](auto stream) {
5823 return hasStream(streams, stream) && isStreamActive(stream, 0);
5824 };
Eric Laurent484e9272018-06-07 17:29:23 -07005825
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305826 auto doGetOutputDevicesForVoice = [&]() {
5827 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
5828 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL))) &&
5829 (isInCall() ||
5830 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc));
5831 };
5832
5833 // With low-latency playing on speaker, music on WFD, when the first low-latency
5834 // output is stopped, getNewOutputDevices checks for a product strategy
5835 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
5836 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
5837 // devices are returned for STRATEGY_SONIFICATION without checking whether the
5838 // stream is associated to the output descriptor.
5839 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
5840 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
5841 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
5842 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01005843 // Retrieval of devices for voice DL is done on primary output profile, cannot
5844 // check the route (would force modifying configuration file for this profile)
5845 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5846 break;
5847 }
Eric Laurente552edb2014-03-10 17:42:56 -07005848 }
François Gaffiec005e562018-11-06 15:04:49 +01005849 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01005850 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005851}
5852
François Gaffie11d30102018-11-02 16:09:09 +01005853sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5854 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005855{
François Gaffie11d30102018-11-02 16:09:09 +01005856 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005857
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005858 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005859 if (index >= 0) {
5860 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005861 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005862 ALOGV("getNewInputDevice() device %s forced by patch %d",
5863 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5864 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005865 }
5866 }
5867
Eric Laurent97ac8712018-07-27 18:59:02 -07005868 // Honor explicit routing requests only if no client using default routing is active on this
5869 // input: a specific app can not force routing for other apps by setting a preferred device.
5870 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005871 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5872 if (device != nullptr) {
5873 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005874 }
5875
Eric Laurentdc95a252018-04-12 12:46:56 -07005876 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005877 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08005878 audio_attributes_t attributes;
5879 uid_t uid;
5880 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
5881 if (topClient != nullptr) {
5882 attributes = topClient->attributes();
5883 uid = topClient->uid();
5884 } else {
5885 attributes = { .source = AUDIO_SOURCE_DEFAULT };
5886 uid = 0;
5887 }
5888
Francois Gaffie716e1432019-01-14 16:58:59 +01005889 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5890 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005891 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005892 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08005893 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005894 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005895
Eric Laurente552edb2014-03-10 17:42:56 -07005896 return device;
5897}
5898
Eric Laurent794fde22016-03-11 09:50:45 -08005899bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5900 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005901 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005902}
5903
Eric Laurente0720872014-03-11 09:30:41 -07005904audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005905 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005906 // getOutputDevicesForStream's behavior for invalid streams.
5907 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5908 // device for music stream), but we want to return the empty set.
5909 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005910 return AUDIO_DEVICE_NONE;
5911 }
François Gaffie11d30102018-11-02 16:09:09 +01005912 DeviceVector activeDevices;
5913 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00005914 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
5915 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01005916 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005917 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005918 }
François Gaffiec005e562018-11-06 15:04:49 +01005919 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005920 devices.merge(curDevices);
5921 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005922 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07005923 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01005924 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005925 }
5926 }
Eric Laurente552edb2014-03-10 17:42:56 -07005927 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005928
Eric Laurentb0688d62018-08-14 15:49:18 -07005929 // Favor devices selected on active streams if any to report correct device in case of
5930 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005931 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005932 devices = activeDevices;
5933 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005934 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5935 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07005936 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01005937 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07005938 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01005939 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005940 }
jiabin9a3361e2019-10-01 09:38:30 -07005941 // FIXME: use DeviceTypeSet when Java layer is ready for it.
5942 return deviceTypesToBitMask(devices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005943}
5944
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005945status_t AudioPolicyManager::getDevicesForAttributes(
5946 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
5947 if (devices == nullptr) {
5948 return BAD_VALUE;
5949 }
5950 // check dynamic policies but only for primary descriptors (secondary not used for audible
5951 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07005952 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005953 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07005954 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005955 if (status != OK) {
5956 return status;
5957 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005958 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
5959 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
5960 devices->push_back(device);
5961 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005962 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005963 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5964 for (const auto& device : curDevices) {
5965 devices->push_back(device->getDeviceTypeAddr());
5966 }
5967 return NO_ERROR;
5968}
5969
Eric Laurente0720872014-03-11 09:30:41 -07005970void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005971 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005972 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01005973 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005974 updateDevicesAndOutputs();
5975 break;
5976 default:
5977 break;
5978 }
5979}
5980
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005981uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005982
5983 // skip beacon mute management if a dedicated TTS output is available
5984 if (mTtsOutputAvailable) {
5985 return 0;
5986 }
5987
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005988 switch(event) {
5989 case STARTING_OUTPUT:
5990 mBeaconMuteRefCount++;
5991 break;
5992 case STOPPING_OUTPUT:
5993 if (mBeaconMuteRefCount > 0) {
5994 mBeaconMuteRefCount--;
5995 }
5996 break;
5997 case STARTING_BEACON:
5998 mBeaconPlayingRefCount++;
5999 break;
6000 case STOPPING_BEACON:
6001 if (mBeaconPlayingRefCount > 0) {
6002 mBeaconPlayingRefCount--;
6003 }
6004 break;
6005 }
6006
6007 if (mBeaconMuteRefCount > 0) {
6008 // any playback causes beacon to be muted
6009 return setBeaconMute(true);
6010 } else {
6011 // no other playback: unmute when beacon starts playing, mute when it stops
6012 return setBeaconMute(mBeaconPlayingRefCount == 0);
6013 }
6014}
6015
6016uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6017 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6018 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6019 // keep track of muted state to avoid repeating mute/unmute operations
6020 if (mBeaconMuted != mute) {
6021 // mute/unmute AUDIO_STREAM_TTS on all outputs
6022 ALOGV("\t muting %d", mute);
6023 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01006024 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006025 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006026 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006027 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006028 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006029 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006030 maxLatency = latency;
6031 }
6032 }
6033 mBeaconMuted = mute;
6034 return maxLatency;
6035 }
6036 return 0;
6037}
6038
Eric Laurente0720872014-03-11 09:30:41 -07006039void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006040{
François Gaffiec005e562018-11-06 15:04:49 +01006041 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006042 mPreviousOutputs = mOutputs;
6043}
6044
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006045uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006046 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006047 uint32_t delayMs)
6048{
6049 // mute/unmute strategies using an incompatible device combination
6050 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6051 // if unmuting, unmute only after the specified delay
6052 if (outputDesc->isDuplicated()) {
6053 return 0;
6054 }
6055
6056 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006057 DeviceVector devices = outputDesc->devices();
6058 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006059
François Gaffiec005e562018-11-06 15:04:49 +01006060 auto productStrategies = mEngine->getOrderedProductStrategies();
6061 for (const auto &productStrategy : productStrategies) {
6062 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6063 DeviceVector curDevices =
6064 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6065 curDevices = curDevices.filter(outputDesc->supportedDevices());
6066 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006067 bool doMute = false;
6068
François Gaffiec005e562018-11-06 15:04:49 +01006069 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006070 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006071 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6072 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006073 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006074 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006075 }
Eric Laurent99401132014-05-07 19:48:15 -07006076 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006077 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006078 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006079 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006080 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006081 continue;
6082 }
François Gaffiec005e562018-11-06 15:04:49 +01006083 ALOGVV("%s() %s (curDevice %s)", __func__,
6084 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6085 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6086 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006087 if (mute) {
6088 // FIXME: should not need to double latency if volume could be applied
6089 // immediately by the audioflinger mixer. We must account for the delay
6090 // between now and the next time the audioflinger thread for this output
6091 // will process a buffer (which corresponds to one buffer size,
6092 // usually 1/2 or 1/4 of the latency).
6093 if (muteWaitMs < desc->latency() * 2) {
6094 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006095 }
6096 }
6097 }
6098 }
6099 }
6100 }
6101
Eric Laurent99401132014-05-07 19:48:15 -07006102 // temporary mute output if device selection changes to avoid volume bursts due to
6103 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006104 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006105 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
6106 // temporary mute duration is conservatively set to 4 times the reported latency
6107 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
6108 if (muteWaitMs < tempMuteWaitMs) {
6109 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006110 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006111 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6112 // make sure that we do not start the temporary mute period too early in case of
6113 // delayed device change
6114 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6115 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006116 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006117 }
6118 }
6119
Eric Laurente552edb2014-03-10 17:42:56 -07006120 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6121 if (muteWaitMs > delayMs) {
6122 muteWaitMs -= delayMs;
6123 usleep(muteWaitMs * 1000);
6124 return muteWaitMs;
6125 }
6126 return 0;
6127}
6128
François Gaffie11d30102018-11-02 16:09:09 +01006129uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6130 const DeviceVector &devices,
6131 bool force,
6132 int delayMs,
6133 audio_patch_handle_t *patchHandle,
6134 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006135{
François Gaffie11d30102018-11-02 16:09:09 +01006136 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006137 uint32_t muteWaitMs;
6138
6139 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006140 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6141 nullptr /* patchHandle */, requiresMuteCheck);
6142 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6143 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006144 return muteWaitMs;
6145 }
Eric Laurente552edb2014-03-10 17:42:56 -07006146
6147 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006148 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006149 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07006150
François Gaffie11d30102018-11-02 16:09:09 +01006151 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6152
6153 if (!filteredDevices.isEmpty()) {
6154 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006155 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006156
6157 // if the outputs are not materially active, there is no need to mute.
6158 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006159 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006160 } else {
6161 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6162 muteWaitMs = 0;
6163 }
Eric Laurente552edb2014-03-10 17:42:56 -07006164
Eric Laurent79ea9582020-06-11 18:49:24 -07006165 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6166 // output profile or if new device is not supported AND previous device(s) is(are) still
6167 // available (otherwise reset device must be done on the output)
6168 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
6169 !mAvailableOutputDevices.filter(prevDevices).empty()) {
6170 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6171 // restore previous device after evaluating strategy mute state
6172 outputDesc->setDevices(prevDevices);
6173 return muteWaitMs;
6174 }
6175
Eric Laurente552edb2014-03-10 17:42:56 -07006176 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006177 // the requested device is AUDIO_DEVICE_NONE
6178 // OR the requested device is the same as current device
6179 // AND force is not specified
6180 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006181 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006182 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01006183 !force && outputDesc->getPatchHandle() != 0) {
6184 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6185 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07006186 return muteWaitMs;
6187 }
6188
François Gaffie11d30102018-11-02 16:09:09 +01006189 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006190
Eric Laurente552edb2014-03-10 17:42:56 -07006191 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01006192 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006193 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006194 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006195 PatchBuilder patchBuilder;
6196 patchBuilder.addSource(outputDesc);
6197 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6198 for (const auto &filteredDevice : filteredDevices) {
6199 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006200 }
6201
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006202 // Add half reported latency to delayMs when muteWaitMs is null in order
6203 // to avoid disordered sequence of muting volume and changing devices.
6204 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6205 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006206 }
Eric Laurente552edb2014-03-10 17:42:56 -07006207
6208 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006209 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006210
6211 return muteWaitMs;
6212}
6213
Eric Laurentc75307b2015-03-17 15:29:32 -07006214status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006215 int delayMs,
6216 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006217{
Eric Laurent6a94d692014-05-20 11:18:06 -07006218 ssize_t index;
6219 if (patchHandle) {
6220 index = mAudioPatches.indexOfKey(*patchHandle);
6221 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006222 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006223 }
6224 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006225 return INVALID_OPERATION;
6226 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006227 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006228 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006229 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006230 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006231 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006232 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006233 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006234 return status;
6235}
6236
6237status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006238 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006239 bool force,
6240 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006241{
6242 status_t status = NO_ERROR;
6243
Eric Laurent1f2f2232014-06-02 12:01:23 -07006244 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006245 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6246 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006247
François Gaffie11d30102018-11-02 16:09:09 +01006248 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006249 PatchBuilder patchBuilder;
6250 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006251 // AUDIO_SOURCE_HOTWORD is for internal use only:
6252 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006253 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6254 auto result = usecase;
6255 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6256 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6257 }
6258 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006259 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006260 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006261 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006262 }
6263 }
6264 return status;
6265}
6266
Eric Laurent6a94d692014-05-20 11:18:06 -07006267status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6268 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006269{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006270 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006271 ssize_t index;
6272 if (patchHandle) {
6273 index = mAudioPatches.indexOfKey(*patchHandle);
6274 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006275 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006276 }
6277 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006278 return INVALID_OPERATION;
6279 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006280 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006281 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006282 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006283 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006284 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006285 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006286 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006287 return status;
6288}
6289
François Gaffie11d30102018-11-02 16:09:09 +01006290sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006291 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006292 audio_format_t& format,
6293 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006294 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006295{
6296 // Choose an input profile based on the requested capture parameters: select the first available
6297 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006298 //
6299 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6300 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006301
Glenn Kasten730b9262018-03-29 15:01:26 -07006302 sp<IOProfile> firstInexact;
6303 uint32_t updatedSamplingRate = 0;
6304 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6305 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006306 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006307 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006308 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006309 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006310 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006311 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006312 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006313 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006314 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006315 &channelMask /*updatedChannelMask*/,
6316 // FIXME ugly cast
6317 (audio_output_flags_t) flags,
6318 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006319 return profile;
6320 }
François Gaffie11d30102018-11-02 16:09:09 +01006321 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006322 samplingRate,
6323 &updatedSamplingRate,
6324 format,
6325 &updatedFormat,
6326 channelMask,
6327 &updatedChannelMask,
6328 // FIXME ugly cast
6329 (audio_output_flags_t) flags,
6330 false /*exactMatchRequiredForInputFlags*/)) {
6331 firstInexact = profile;
6332 }
6333
Eric Laurente552edb2014-03-10 17:42:56 -07006334 }
6335 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006336 if (firstInexact != nullptr) {
6337 samplingRate = updatedSamplingRate;
6338 format = updatedFormat;
6339 channelMask = updatedChannelMask;
6340 return firstInexact;
6341 }
Eric Laurente552edb2014-03-10 17:42:56 -07006342 return NULL;
6343}
6344
François Gaffieaaac0fd2018-11-22 17:56:39 +01006345float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6346 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006347 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006348 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006349{
jiabin9a3361e2019-10-01 09:38:30 -07006350 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006351
6352 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6353 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6354 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6355 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006356 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6357 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6358 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6359 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006360 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006361
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006362 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006363 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6364 mOutputs.isActive(ringVolumeSrc, 0)) {
6365 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006366 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006367 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006368 }
6369
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006370 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006371 if ((volumeSource != callVolumeSrc && (isInCall() ||
6372 mOutputs.isActiveLocally(callVolumeSrc))) &&
6373 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6374 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6375 volumeSource == alarmVolumeSrc ||
6376 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6377 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6378 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006379 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006380 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006381 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006382 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006383 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006384 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006385 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6386 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6387 // programmatically muted.
6388 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6389 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6390 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006391 bool exemptFromCapping =
6392 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6393 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006394 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6395 volumeSource, volumeDb);
6396 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006397 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6398 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6399 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006400 }
6401 }
Eric Laurente552edb2014-03-10 17:42:56 -07006402 // if a headset is connected, apply the following rules to ring tones and notifications
6403 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006404 // - always attenuate notifications volume by 6dB
6405 // - attenuate ring tones volume by 6dB unless music is not playing and
6406 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006407 // - if music is playing, always limit the volume to current music volume,
6408 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006409 if (!Intersection(deviceTypes,
6410 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6411 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006412 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6413 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006414 ((volumeSource == alarmVolumeSrc ||
6415 volumeSource == ringVolumeSrc) ||
6416 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6417 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6418 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6419 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6420 curves.canBeMuted()) {
6421
Eric Laurente552edb2014-03-10 17:42:56 -07006422 // when the phone is ringing we must consider that music could have been paused just before
6423 // by the music application and behave as if music was active if the last music track was
6424 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006425 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006426 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006427 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006428 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006429 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6430 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006431 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006432 float musicVolDb = computeVolume(musicCurves,
6433 musicVolumeSrc,
6434 musicCurves.getVolumeIndex(musicDevice),
6435 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006436 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6437 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6438 if (volumeDb > minVolDb) {
6439 volumeDb = minVolDb;
6440 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006441 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02006442 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
6443 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6444 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006445 // on A2DP, also ensure notification volume is not too low compared to media when
6446 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006447 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006448 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006449 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6450 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006451 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6452 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006453 }
6454 }
jiabin9a3361e2019-10-01 09:38:30 -07006455 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006456 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006457 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006458 }
6459 }
6460
François Gaffie43c73442018-11-08 08:21:55 +01006461 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006462}
6463
Eric Laurent3839bc02018-07-10 18:33:34 -07006464int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006465 VolumeSource fromVolumeSource,
6466 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006467{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006468 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006469 return srcIndex;
6470 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006471 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6472 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006473 float minSrc = (float)srcCurves.getVolumeIndexMin();
6474 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6475 float minDst = (float)dstCurves.getVolumeIndexMin();
6476 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006477
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006478 // preserve mute request or correct range
6479 if (srcIndex < minSrc) {
6480 if (srcIndex == 0) {
6481 return 0;
6482 }
6483 srcIndex = minSrc;
6484 } else if (srcIndex > maxSrc) {
6485 srcIndex = maxSrc;
6486 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006487 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6488}
6489
François Gaffieaaac0fd2018-11-22 17:56:39 +01006490status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6491 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006492 int index,
6493 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006494 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006495 int delayMs,
6496 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006497{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006498 // do not change actual attributes volume if the attributes is muted
6499 if (outputDesc->isMuted(volumeSource)) {
6500 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6501 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006502 return NO_ERROR;
6503 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006504 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6505 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
6506 bool isVoiceVolSrc = callVolSrc == volumeSource;
6507 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
6508
Eric Laurent2517af32020-11-25 15:31:27 +01006509 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006510 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006511 // if sco and call follow same curves, bypass forceUseForComm
6512 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006513 ((isVoiceVolSrc && isScoRequested) ||
6514 (isBtScoVolSrc && !isScoRequested))) {
6515 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6516 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07006517 // Do not return an error here as AudioService will always set both voice call
6518 // and bluetooth SCO volumes due to stream aliasing.
6519 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006520 }
jiabin9a3361e2019-10-01 09:38:30 -07006521 if (deviceTypes.empty()) {
6522 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006523 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006524
jiabin9a3361e2019-10-01 09:38:30 -07006525 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6526 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07006527 // Force VoIP volume to max for bluetooth SCO device except if muted
6528 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07006529 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006530 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006531 }
jiabin9a3361e2019-10-01 09:38:30 -07006532 outputDesc->setVolume(
6533 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006534
François Gaffieaaac0fd2018-11-22 17:56:39 +01006535 if (isVoiceVolSrc || isBtScoVolSrc) {
Eric Laurente552edb2014-03-10 17:42:56 -07006536 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006537 // 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 +01006538 if (isVoiceVolSrc) {
6539 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006540 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006541 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006542 }
Eric Laurent18fba842016-03-31 14:41:26 -07006543 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006544 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6545 mLastVoiceVolume = voiceVolume;
6546 }
6547 }
Eric Laurente552edb2014-03-10 17:42:56 -07006548 return NO_ERROR;
6549}
6550
Eric Laurentc75307b2015-03-17 15:29:32 -07006551void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006552 const DeviceTypeSet& deviceTypes,
6553 int delayMs,
6554 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006555{
jiabincd510522020-01-22 09:40:55 -08006556 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006557 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6558 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6559 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07006560 curves.getVolumeIndex(deviceTypes),
6561 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006562 }
6563}
6564
François Gaffiec005e562018-11-06 15:04:49 +01006565void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6566 bool on,
6567 const sp<AudioOutputDescriptor>& outputDesc,
6568 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006569 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006570{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006571 std::vector<VolumeSource> sourcesToMute;
6572 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6573 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6574 toString(attributes).c_str(), on, outputDesc->getId());
6575 VolumeSource source = toVolumeSource(attributes);
6576 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
6577 sourcesToMute.push_back(source);
6578 }
Eric Laurente552edb2014-03-10 17:42:56 -07006579 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006580 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07006581 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006582 }
6583
Eric Laurente552edb2014-03-10 17:42:56 -07006584}
6585
François Gaffieaaac0fd2018-11-22 17:56:39 +01006586void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6587 bool on,
6588 const sp<AudioOutputDescriptor>& outputDesc,
6589 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006590 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006591{
jiabin9a3361e2019-10-01 09:38:30 -07006592 if (deviceTypes.empty()) {
6593 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006594 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006595 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006596 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006597 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006598 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006599 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6600 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6601 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07006602 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006603 }
6604 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006605 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6606 // ignored
6607 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006608 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006609 if (!outputDesc->isMuted(volumeSource)) {
6610 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006611 return;
6612 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006613 if (outputDesc->decMuteCount(volumeSource) == 0) {
6614 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07006615 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006616 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006617 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006618 delayMs);
6619 }
6620 }
6621}
6622
François Gaffie53615e22015-03-19 09:24:12 +01006623bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6624{
François Gaffiec005e562018-11-06 15:04:49 +01006625 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006626 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6627 return true;
6628 }
6629
6630 // has known usage?
6631 switch (paa->usage) {
6632 case AUDIO_USAGE_UNKNOWN:
6633 case AUDIO_USAGE_MEDIA:
6634 case AUDIO_USAGE_VOICE_COMMUNICATION:
6635 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6636 case AUDIO_USAGE_ALARM:
6637 case AUDIO_USAGE_NOTIFICATION:
6638 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6639 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6640 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6641 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6642 case AUDIO_USAGE_NOTIFICATION_EVENT:
6643 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6644 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6645 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6646 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006647 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006648 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006649 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006650 case AUDIO_USAGE_EMERGENCY:
6651 case AUDIO_USAGE_SAFETY:
6652 case AUDIO_USAGE_VEHICLE_STATUS:
6653 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006654 break;
6655 default:
6656 return false;
6657 }
6658 return true;
6659}
6660
François Gaffie2110e042015-03-24 08:41:51 +01006661audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6662{
6663 return mEngine->getForceUse(usage);
6664}
6665
6666bool AudioPolicyManager::isInCall()
6667{
6668 return isStateInCall(mEngine->getPhoneState());
6669}
6670
6671bool AudioPolicyManager::isStateInCall(int state)
6672{
6673 return is_state_in_call(state);
6674}
6675
Eric Laurent74b71512019-11-06 17:21:57 -08006676bool AudioPolicyManager::isCallAudioAccessible()
6677{
6678 audio_mode_t mode = mEngine->getPhoneState();
6679 return (mode == AUDIO_MODE_IN_CALL)
6680 || (mode == AUDIO_MODE_IN_COMMUNICATION)
6681 || (mode == AUDIO_MODE_CALL_SCREEN);
6682}
6683
Eric Laurentd60560a2015-04-10 11:31:20 -07006684void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6685{
6686 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006687 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006688 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006689 sourceDesc->sinkDevice()->equals(deviceDesc))
6690 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006691 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006692 }
6693 }
6694
6695 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6696 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6697 bool release = false;
6698 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6699 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6700 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6701 source->ext.device.type == deviceDesc->type()) {
6702 release = true;
6703 }
6704 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006705 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07006706 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6707 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6708 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006709 sink->ext.device.type == deviceDesc->type() &&
6710 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
6711 || strncmp(sink->ext.device.address, address,
6712 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006713 release = true;
6714 }
6715 }
6716 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006717 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6718 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006719 }
6720 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006721
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006722 mInputs.clearSessionRoutesForDevice(deviceDesc);
6723
Francois Gaffie716e1432019-01-14 16:58:59 +01006724 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006725}
6726
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006727void AudioPolicyManager::modifySurroundFormats(
6728 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006729 std::unordered_set<audio_format_t> enforcedSurround(
6730 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006731 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6732 for (const auto& pair : mConfig.getSurroundFormats()) {
6733 allSurround.insert(pair.first);
6734 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6735 }
Phil Burk09bc4612016-02-24 15:58:15 -08006736
6737 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6738 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07006739 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006740 // This is the resulting set of formats depending on the surround mode:
6741 // 'all surround' = allSurround
6742 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
6743 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
6744 // 'manual surround' = mManualSurroundFormats
6745 // AUTO: formats v 'enforced surround'
6746 // ALWAYS: formats v 'all surround' v 'enforced surround'
6747 // NEVER: formats ^ 'non-surround'
6748 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08006749
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006750 std::unordered_set<audio_format_t> formatSet;
6751 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
6752 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006753 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006754 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006755 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006756 formatSet.insert(*formatIter);
6757 }
6758 }
6759 } else {
6760 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6761 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006762 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006763
jiabin81772902018-04-02 17:52:27 -07006764 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006765 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006766 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6767 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6768 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08006769 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006770 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6771 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6772 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07006773 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006774 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08006775 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006776 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07006777 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006778 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006779}
6780
jiabin06e4bab2019-07-29 10:13:34 -07006781void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
6782 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07006783 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6784 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6785
6786 // If NEVER, then remove support for channelMasks > stereo.
6787 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07006788 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
6789 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006790 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006791 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07006792 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07006793 } else {
jiabin06e4bab2019-07-29 10:13:34 -07006794 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006795 }
6796 }
jiabin81772902018-04-02 17:52:27 -07006797 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6798 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6799 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006800 bool supports5dot1 = false;
6801 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006802 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006803 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6804 supports5dot1 = true;
6805 break;
6806 }
6807 }
6808 // If not then add 5.1 support.
6809 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07006810 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01006811 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006812 }
Phil Burk09bc4612016-02-24 15:58:15 -08006813 }
6814}
6815
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006816void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006817 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006818 AudioProfileVector &profiles)
6819{
6820 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006821 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006822
François Gaffie112b0af2015-11-19 16:13:25 +01006823 // Format MUST be checked first to update the list of AudioProfile
6824 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006825 reply = mpClientInterface->getParameters(
6826 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006827 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006828 AudioParameter repliedParameters(reply);
6829 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006830 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006831 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6832 return;
6833 }
Phil Burk09bc4612016-02-24 15:58:15 -08006834 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01006835 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006836 if (device == AUDIO_DEVICE_OUT_HDMI
6837 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006838 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006839 }
jiabin3e277cc2019-09-10 14:27:34 -07006840 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006841 }
François Gaffie112b0af2015-11-19 16:13:25 +01006842
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006843 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07006844 ChannelMaskSet channelMasks;
6845 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006846 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006847 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006848
6849 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006850 reply = mpClientInterface->getParameters(
6851 ioHandle,
6852 requestedParameters.toString() + ";" +
6853 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006854 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006855 AudioParameter repliedParameters(reply);
6856 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006857 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006858 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006859 }
6860 }
6861 if (profiles.hasDynamicChannelsFor(format)) {
6862 reply = mpClientInterface->getParameters(ioHandle,
6863 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006864 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006865 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006866 AudioParameter repliedParameters(reply);
6867 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006868 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006869 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006870 if (device == AUDIO_DEVICE_OUT_HDMI
6871 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006872 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006873 }
François Gaffie112b0af2015-11-19 16:13:25 +01006874 }
6875 }
jiabin3e277cc2019-09-10 14:27:34 -07006876 addDynamicAudioProfileAndSort(
6877 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006878 }
6879}
Eric Laurentd60560a2015-04-10 11:31:20 -07006880
Mikhail Naganovdc769682018-05-04 15:34:08 -07006881status_t AudioPolicyManager::installPatch(const char *caller,
6882 audio_patch_handle_t *patchHandle,
6883 AudioIODescriptorInterface *ioDescriptor,
6884 const struct audio_patch *patch,
6885 int delayMs)
6886{
6887 ssize_t index = mAudioPatches.indexOfKey(
6888 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6889 *patchHandle : ioDescriptor->getPatchHandle());
6890 sp<AudioPatch> patchDesc;
6891 status_t status = installPatch(
6892 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6893 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006894 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07006895 }
6896 return status;
6897}
6898
6899status_t AudioPolicyManager::installPatch(const char *caller,
6900 ssize_t index,
6901 audio_patch_handle_t *patchHandle,
6902 const struct audio_patch *patch,
6903 int delayMs,
6904 uid_t uid,
6905 sp<AudioPatch> *patchDescPtr)
6906{
6907 sp<AudioPatch> patchDesc;
6908 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6909 if (index >= 0) {
6910 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006911 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006912 }
6913
6914 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6915 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6916 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6917 if (status == NO_ERROR) {
6918 if (index < 0) {
6919 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01006920 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006921 } else {
6922 patchDesc->mPatch = *patch;
6923 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006924 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006925 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006926 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006927 }
6928 nextAudioPortGeneration();
6929 mpClientInterface->onAudioPatchListUpdate();
6930 }
6931 if (patchDescPtr) *patchDescPtr = patchDesc;
6932 return status;
6933}
6934
jiabinbce0c1d2020-10-05 11:20:18 -07006935bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
6936{
6937 const TrackClientVector activeClients = output->getActiveClients();
6938 if (activeClients.empty()) {
6939 return true;
6940 }
6941 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
6942 if (index < 0) {
6943 ALOGE("%s, no audio patch found while there are active clients on output %d",
6944 __func__, output->getId());
6945 return false;
6946 }
6947 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6948 DeviceVector routedDevices;
6949 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
6950 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
6951 patchDesc->mPatch.sinks[i].id);
6952 if (device == nullptr) {
6953 ALOGE("%s, no audio device found with id(%d)",
6954 __func__, patchDesc->mPatch.sinks[i].id);
6955 return false;
6956 }
6957 routedDevices.add(device);
6958 }
6959 for (const auto& client : activeClients) {
6960 // TODO: b/175343099 only travel the valid client
6961 sp<DeviceDescriptor> preferredDevice =
6962 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
6963 if (mEngine->getOutputDevicesForAttributes(
6964 client->attributes(), preferredDevice, false) == routedDevices) {
6965 return false;
6966 }
6967 }
6968 return true;
6969}
6970
6971sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
6972 const sp<IOProfile>& profile, const DeviceVector& devices)
6973{
6974 for (const auto& device : devices) {
6975 // TODO: This should be checking if the profile supports the device combo.
6976 if (!profile->supportsDevice(device)) {
6977 return nullptr;
6978 }
6979 }
6980 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
6981 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
6982 status_t status = desc->open(nullptr, devices,
6983 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
6984 if (status != NO_ERROR) {
6985 return nullptr;
6986 }
6987
6988 // Here is where the out_set_parameters() for card & device gets called
6989 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
6990 const audio_devices_t deviceType = device->type();
6991 const String8 &address = String8(device->address().c_str());
6992 if (!address.isEmpty()) {
6993 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
6994 mpClientInterface->setParameters(output, String8(param));
6995 free(param);
6996 }
6997 updateAudioProfiles(device, output, profile->getAudioProfiles());
6998 if (!profile->hasValidAudioProfile()) {
6999 ALOGW("%s() missing param", __func__);
7000 desc->close();
7001 return nullptr;
7002 } else if (profile->hasDynamicAudioProfile()) {
7003 desc->close();
7004 output = AUDIO_IO_HANDLE_NONE;
7005 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7006 profile->pickAudioProfile(
7007 config.sample_rate, config.channel_mask, config.format);
7008 config.offload_info.sample_rate = config.sample_rate;
7009 config.offload_info.channel_mask = config.channel_mask;
7010 config.offload_info.format = config.format;
7011
7012 status = desc->open(&config, devices,
7013 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7014 if (status != NO_ERROR) {
7015 return nullptr;
7016 }
7017 }
7018
7019 addOutput(output, desc);
7020 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7021 sp<AudioPolicyMix> policyMix;
7022 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7023 policyMix->setOutput(desc);
7024 desc->mPolicyMix = policyMix;
7025 } else {
7026 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7027 address.string());
7028 }
7029
7030 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && hasPrimaryOutput()) {
7031 // no duplicated output for direct outputs and
7032 // outputs used by dynamic policy mixes
7033 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7034
7035 //TODO: configure audio effect output stage here
7036
7037 // open a duplicating output thread for the new output and the primary output
7038 sp<SwAudioOutputDescriptor> dupOutputDesc =
7039 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7040 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7041 if (status == NO_ERROR) {
7042 // add duplicated output descriptor
7043 addOutput(duplicatedOutput, dupOutputDesc);
7044 } else {
7045 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7046 mPrimaryOutput->mIoHandle, output);
7047 desc->close();
7048 removeOutput(output);
7049 nextAudioPortGeneration();
7050 return nullptr;
7051 }
7052 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007053 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7054 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7055 mPrimaryOutput = desc;
7056 }
jiabinbce0c1d2020-10-05 11:20:18 -07007057 return desc;
7058}
7059
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007060} // namespace android