blob: 5b53c0ba38778410283a2c019b6fe918c9a7ceed [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 Naganov8916ae92020-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 Naganov8916ae92020-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 Naganovedc0ae12020-04-14 14:47:01 -070046#include <system/audio_config.h>
Mikhail Naganov8916ae92020-10-21 13:04:58 -070047#include <utils/Log.h>
48
Eric Laurentd4692962014-05-05 18:13:44 -070049#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010050#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070051
Eric Laurent3b73df72014-03-11 09:06:29 -070052namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070053
Eric Laurentdc462862016-07-19 12:29:53 -070054//FIXME: workaround for truncated touch sounds
55// to be removed when the problem is handled by system UI
56#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070057
58// Largest difference in dB on earpiece in call between the voice volume and another
59// media / notification / system volume.
60constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
61
Mikhail Naganov15be9d22017-11-08 14:18:13 +110062// Compressed formats for MSD module, ordered from most preferred to least preferred.
Dean Wheatley5cbec5a2021-02-10 16:02:23 +110063static const std::vector<audio_format_t> msdCompressedFormatsOrder = {{
64 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Mikhail Naganov15be9d22017-11-08 14:18:13 +110065 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
66// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
Dean Wheatley5cbec5a2021-02-10 16:02:23 +110067static const std::vector<audio_channel_mask_t> msdSurroundChannelMasksOrder = {{
Mikhail Naganov15be9d22017-11-08 14:18:13 +110068 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
69 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
70 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
71
jiabin4562b3b2019-07-29 10:13:34 -070072template <typename T>
73bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
74{
75 if (left.size() != right.size()) {
76 return false;
77 }
78 for (size_t index = 0; index < right.size(); index++) {
79 if (left[index] != right[index]) {
80 return false;
81 }
82 }
83 return true;
84}
85
86template <typename T>
87bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
88{
89 return !(left == right);
90}
91
Eric Laurente552edb2014-03-10 17:42:56 -070092// ----------------------------------------------------------------------------
93// AudioPolicyInterface implementation
94// ----------------------------------------------------------------------------
95
Eric Laurente0720872014-03-11 09:30:41 -070096status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080097 audio_policy_dev_state_t state,
98 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -080099 const char *device_name,
100 audio_format_t encodedFormat)
Eric Laurente552edb2014-03-10 17:42:56 -0700101{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800102 status_t status = setDeviceConnectionStateInt(device, state, device_address,
103 device_name, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800104 nextAudioPortGeneration();
105 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800106}
107
François Gaffie11d30102018-11-02 16:09:09 +0100108void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
109 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200110{
jiabin6713a382019-09-12 16:29:15 -0700111 AudioParameter param(String8(device->address().c_str()));
François Gaffie44481e72016-04-20 07:49:57 +0200112 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganovbb3b1602019-07-08 15:28:43 -0700113 AudioParameter::keyDeviceConnect : AudioParameter::keyDeviceDisconnect);
François Gaffie11d30102018-11-02 16:09:09 +0100114 param.addInt(key, device->type());
François Gaffie44481e72016-04-20 07:49:57 +0200115 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
116}
117
François Gaffie11d30102018-11-02 16:09:09 +0100118status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800119 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800120 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800121 const char *device_name,
122 audio_format_t encodedFormat)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800123{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800124 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s format 0x%X",
125 deviceType, state, device_address, device_name, encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700126
127 // connect/disconnect only 1 device at a time
François Gaffie11d30102018-11-02 16:09:09 +0100128 if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -0700129
François Gaffie11d30102018-11-02 16:09:09 +0100130 sp<DeviceDescriptor> device =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800131 mHwModules.getDeviceDescriptor(deviceType, device_address, device_name, encodedFormat,
Francois Gaffie716e1432019-01-14 16:58:59 +0100132 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganova30ec142020-03-24 09:32:34 -0700133 return device ? setDeviceConnectionStateInt(device, state) : INVALID_OPERATION;
134}
Paul McLeane743a472015-01-28 11:07:31 -0800135
Mikhail Naganova30ec142020-03-24 09:32:34 -0700136status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
137 audio_policy_dev_state_t state)
138{
Eric Laurente552edb2014-03-10 17:42:56 -0700139 // handle output devices
Mikhail Naganova30ec142020-03-24 09:32:34 -0700140 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700141 SortedVector <audio_io_handle_t> outputs;
142
François Gaffie11d30102018-11-02 16:09:09 +0100143 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700144
Eric Laurente552edb2014-03-10 17:42:56 -0700145 // save a copy of the opened output descriptors before any output is opened or closed
146 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
147 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700148 switch (state)
149 {
150 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800151 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700152 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100153 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700154 return INVALID_OPERATION;
155 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800156 ALOGV("%s() connecting device %s format %x",
Mikhail Naganova30ec142020-03-24 09:32:34 -0700157 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700158
Eric Laurente552edb2014-03-10 17:42:56 -0700159 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200160 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700161 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700162 }
163
François Gaffie44481e72016-04-20 07:49:57 +0200164 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
165 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100166 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200167
François Gaffie11d30102018-11-02 16:09:09 +0100168 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
169 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200170
Francois Gaffie716e1432019-01-14 16:58:59 +0100171 mHwModules.cleanUpForDevice(device);
172
François Gaffie11d30102018-11-02 16:09:09 +0100173 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700174 return INVALID_OPERATION;
175 }
François Gaffie2110e042015-03-24 08:41:51 +0100176
jiabin1c4794b2020-05-05 10:08:05 -0700177 // Populate encapsulation information when a output device is connected.
178 device->setEncapsulationInfoFromHal(mpClientInterface);
179
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700180 // outputs should never be empty here
181 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
182 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100183 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800184
Eric Laurent3ae5f312015-02-03 17:12:08 -0800185 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700186 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700187 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700188 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100189 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700190 return INVALID_OPERATION;
191 }
192
François Gaffie11d30102018-11-02 16:09:09 +0100193 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700194
Paul McLeane743a472015-01-28 11:07:31 -0800195 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100196 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700197
Eric Laurente552edb2014-03-10 17:42:56 -0700198 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100199 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700200
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100201 mOutputs.clearSessionRoutesForDevice(device);
202
François Gaffie11d30102018-11-02 16:09:09 +0100203 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100204
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800205 // Reset active device codec
206 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
207
Eric Laurente552edb2014-03-10 17:42:56 -0700208 } break;
209
210 default:
François Gaffie11d30102018-11-02 16:09:09 +0100211 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700212 return BAD_VALUE;
213 }
214
Eric Laurent736a1022019-03-27 18:28:46 -0700215 // Propagate device availability to Engine
216 setEngineDeviceConnectionState(device, state);
217
Eric Laurentae970022019-01-29 14:25:04 -0800218 // No need to evaluate playback routing when connecting a remote submix
219 // output device used by a dynamic policy of type recorder as no
220 // playback use case is affected.
221 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganova30ec142020-03-24 09:32:34 -0700222 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800223 for (audio_io_handle_t output : outputs) {
224 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800225 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
226 if (policyMix != nullptr
227 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganova30ec142020-03-24 09:32:34 -0700228 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800229 doCheckForDeviceAndOutputChanges = false;
230 break;
231 }
232 }
233 }
234
235 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700236 // outputs must be closed after checkOutputForAllStrategies() is executed
237 if (!outputs.isEmpty()) {
238 for (audio_io_handle_t output : outputs) {
239 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100240 // close unused outputs after device disconnection or direct outputs that have
241 // been opened by checkOutputsForDevice() to query dynamic parameters
Mikhail Naganov37977152018-07-11 15:54:44 -0700242 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
243 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurentae970022019-01-29 14:25:04 -0800244 (desc->mDirectOpenCount == 0))) {
Francois Gaffie5bd3d2d2020-05-06 18:37:04 +0200245 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700246 closeOutput(output);
247 }
Eric Laurente552edb2014-03-10 17:42:56 -0700248 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700249 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
250 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700251 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700252 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800253 };
254
255 if (doCheckForDeviceAndOutputChanges) {
256 checkForDeviceAndOutputChanges(checkCloseOutputs);
257 } else {
258 checkCloseOutputs();
259 }
Francois Gaffie9da281d2021-02-04 17:02:59 +0100260 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100261 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
Eric Laurente552edb2014-03-10 17:42:56 -0700262 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700263 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
264 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100265 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700266 // do not force device change on duplicated output because if device is 0, it will
267 // also force a device 0 for the two outputs it is duplicated to which may override
268 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100269 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100270 && !desc->isDuplicated()
Mikhail Naganova30ec142020-03-24 09:32:34 -0700271 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700272 // always force when disconnecting (a non-duplicated device)
273 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100274 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700275 }
Eric Laurente552edb2014-03-10 17:42:56 -0700276 }
277
Eric Laurentd60560a2015-04-10 11:31:20 -0700278 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100279 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700280 }
281
Eric Laurent72aa32f2014-05-30 18:51:48 -0700282 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700283 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700284 } // end if is output device
285
Eric Laurente552edb2014-03-10 17:42:56 -0700286 // handle input devices
Mikhail Naganova30ec142020-03-24 09:32:34 -0700287 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100288 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700289 switch (state)
290 {
291 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700292 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700293 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100294 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700295 return INVALID_OPERATION;
296 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700297
298 if (mAvailableInputDevices.add(device) < 0) {
299 return NO_MEMORY;
300 }
301
François Gaffie44481e72016-04-20 07:49:57 +0200302 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
303 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100304 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200305
Eric Laurent0dd51852019-04-19 18:18:58 -0700306 if (checkInputsForDevice(device, state) != NO_ERROR) {
307 mAvailableInputDevices.remove(device);
308
François Gaffie11d30102018-11-02 16:09:09 +0100309 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100310
311 mHwModules.cleanUpForDevice(device);
312
Eric Laurentd4692962014-05-05 18:13:44 -0700313 return INVALID_OPERATION;
314 }
315
Eric Laurentd4692962014-05-05 18:13:44 -0700316 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700317
318 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700319 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700320 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100321 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700322 return INVALID_OPERATION;
323 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700324
François Gaffie11d30102018-11-02 16:09:09 +0100325 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700326
327 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100328 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700329
François Gaffie11d30102018-11-02 16:09:09 +0100330 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700331
332 checkInputsForDevice(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700333 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700334
335 default:
François Gaffie11d30102018-11-02 16:09:09 +0100336 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700337 return BAD_VALUE;
338 }
339
Eric Laurent736a1022019-03-27 18:28:46 -0700340 // Propagate device availability to Engine
341 setEngineDeviceConnectionState(device, state);
342
Eric Laurent0dd51852019-04-19 18:18:58 -0700343 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700344 // As the input device list can impact the output device selection, update
345 // getDeviceForStrategy() cache
346 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700347
Francois Gaffie9da281d2021-02-04 17:02:59 +0100348 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffied2c073b2020-09-29 16:05:07 +0200349 // Reconnect Audio Source
350 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
351 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
352 checkAudioSourceForAttributes(attributes);
353 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700354 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100355 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700356 }
357
Eric Laurentb52c1522014-05-20 11:27:36 -0700358 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700359 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700360 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700361
François Gaffie11d30102018-11-02 16:09:09 +0100362 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700363 return BAD_VALUE;
364}
365
Eric Laurent736a1022019-03-27 18:28:46 -0700366void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
367 audio_policy_dev_state_t state) {
368
369 // the Engine does not have to know about remote submix devices used by dynamic audio policies
370 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
371 return;
372 }
373 mEngine->setDeviceConnectionState(device, state);
374}
375
376
Eric Laurente0720872014-03-11 09:30:41 -0700377audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100378 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700379{
Eric Laurent634b7142016-04-20 13:48:02 -0700380 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800381 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
382 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700383 (strlen(device_address) != 0)/*matchAddress*/);
384
385 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100386 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700387 device, device_address);
388 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
389 }
François Gaffie53615e22015-03-19 09:24:12 +0100390
Eric Laurent3a4311c2014-03-17 12:00:47 -0700391 DeviceVector *deviceVector;
392
Eric Laurente552edb2014-03-10 17:42:56 -0700393 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700394 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700395 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700396 deviceVector = &mAvailableInputDevices;
397 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100398 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700399 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700400 }
Eric Laurent634b7142016-04-20 13:48:02 -0700401
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800402 return (deviceVector->getDevice(
403 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700404 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800405}
406
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800407status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
408 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800409 const char *device_name,
410 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800411{
412 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700413 String8 reply;
414 AudioParameter param;
415 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800416
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800417 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
418 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800419
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800420 // connect/disconnect only 1 device at a time
421 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
422
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800423 // Check if the device is currently connected
jiabin12dc6b02019-10-01 09:38:30 -0700424 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800425 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800426 // Nothing to do: device is not connected
427 return NO_ERROR;
428 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800429 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800430
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700431 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800432 // configure codecs.
433 // Handle two specific cases by sending a set parameter to
434 // configure A2DP codecs. No need to toggle device state.
435 // Case 1: A2DP active device switches from primary to primary
436 // module
437 // Case 2: A2DP device config changes on primary module.
Francois Gaffiefa51ed72020-10-14 16:13:20 +0200438 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin12dc6b02019-10-01 09:38:30 -0700439 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800440 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
441 if (availablePrimaryOutputDevices().contains(devDesc) &&
442 (module != 0 && module->getHandle() == primaryHandle)) {
443 reply = mpClientInterface->getParameters(
444 AUDIO_IO_HANDLE_NONE,
445 String8(AudioParameter::keyReconfigA2dpSupported));
446 AudioParameter repliedParameters(reply);
447 repliedParameters.getInt(
448 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
449 if (isReconfigA2dpSupported) {
450 const String8 key(AudioParameter::keyReconfigA2dp);
451 param.add(key, String8("true"));
452 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
453 devDesc->setEncodedFormat(encodedFormat);
454 return NO_ERROR;
455 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700456 }
457 }
cnx421bd2dcc42020-07-11 14:58:44 +0800458 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
459 for (size_t i = 0; i < mOutputs.size(); i++) {
460 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
461 // mute media strategies and delay device switch by the largest
462 // This avoid sending the music tail into the earpiece or headset.
463 setStrategyMute(musicStrategy, true, desc);
464 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
465 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
466 nullptr, true /*fromCache*/).types());
467 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800468 // Toggle the device state: UNAVAILABLE -> AVAILABLE
469 // This will force reading again the device configuration
470 status = setDeviceConnectionState(device,
471 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800472 device_address, device_name,
473 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800474 if (status != NO_ERROR) {
475 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
476 status);
477 return status;
478 }
479
480 status = setDeviceConnectionState(device,
481 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800482 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800483 if (status != NO_ERROR) {
484 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
485 status);
486 return status;
487 }
488
489 return NO_ERROR;
490}
491
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800492status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
493 std::vector<audio_format_t> *formats)
494{
495 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800496 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800497 std::unordered_set<audio_format_t> formatSet;
498 sp<HwModule> primaryModule =
499 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Lata5b023eb2019-07-03 11:20:36 -0700500 if (primaryModule == nullptr) {
501 ALOGE("%s() unable to get primary module", __func__);
502 return NO_INIT;
503 }
jiabin12dc6b02019-10-01 09:38:30 -0700504 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
505 getAudioDeviceOutAllA2dpSet());
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800506 for (const auto& device : declaredDevices) {
507 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800508 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800509 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800510 return status;
511}
512
Francois Gaffie9da281d2021-02-04 17:02:59 +0100513DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
514{
515 DeviceVector rxSinkdevices{};
516 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
517 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
518 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
519 auto rxSinkDevice = rxSinkdevices.itemAt(0);
520 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
521 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
522 // retrieve Rx Source device descriptor
523 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
524 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
525
526 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
527 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
528 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
529 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
530 return DeviceVector(rxSinkDevice);
531 }
532 }
533 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
534 // the device returned is not necessarily reachable via this output
535 // (filter later by setOutputDevices())
536 return getNewOutputDevices(mPrimaryOutput, fromCache);
537}
538
539status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
540{
541 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
542 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
543 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
544 }
545 return INVALID_OPERATION;
546}
547
548status_t AudioPolicyManager::updateCallRoutingInternal(
549 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700550{
551 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100552 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700553 uint32_t muteWaitMs = 0;
jiabin12dc6b02019-10-01 09:38:30 -0700554 if(!hasPrimaryOutput() ||
555 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie9da281d2021-02-04 17:02:59 +0100556 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700557 }
Francois Gaffie9da281d2021-02-04 17:02:59 +0100558 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100559
Francois Gaffie716e1432019-01-14 16:58:59 +0100560 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100561 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie9da281d2021-02-04 17:02:59 +0100562 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100563
Francois Gaffie9da281d2021-02-04 17:02:59 +0100564 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100565 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700566
Francois Gaffie06e324a2020-10-14 18:02:07 +0200567 disconnectTelephonyRxAudioSource();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700568 // release TX patch if any
569 if (mCallTxPatch != 0) {
François Gaffiead447b72019-11-18 15:50:22 +0100570 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700571 mCallTxPatch.clear();
572 }
573
François Gaffie9eb18552018-11-05 10:33:26 +0100574 auto telephonyRxModule =
jiabin12dc6b02019-10-01 09:38:30 -0700575 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100576 auto telephonyTxModule =
jiabin12dc6b02019-10-01 09:38:30 -0700577 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100578 // retrieve Rx Source and Tx Sink device descriptors
579 sp<DeviceDescriptor> rxSourceDevice =
580 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
581 String8(),
582 AUDIO_FORMAT_DEFAULT);
583 sp<DeviceDescriptor> txSinkDevice =
584 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
585 String8(),
586 AUDIO_FORMAT_DEFAULT);
587
588 // RX and TX Telephony device are declared by Primary Audio HAL
589 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
590 (telephonyRxModule->getHalVersionMajor() >= 3)) {
591 if (rxSourceDevice == 0 || txSinkDevice == 0) {
592 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie9da281d2021-02-04 17:02:59 +0100593 ALOGE("%s() no telephony Tx and/or RX device", __func__);
594 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100595 }
François Gaffiead447b72019-11-18 15:50:22 +0100596 // createAudioPatchInternal now supports both HW / SW bridging
597 createRxPatch = true;
598 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100599 } else {
600 // If the RX device is on the primary HW module, then use legacy routing method for
601 // voice calls via setOutputDevice() on primary output.
602 // Otherwise, create two audio patches for TX and RX path.
603 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
604 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700605 // If the TX device is also on the primary HW module, setOutputDevice() will take care
606 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100607 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
608 (txSinkDevice != 0);
609 }
610 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
611 // Otherwise, create two audio patches for TX and RX path.
612 if (!createRxPatch) {
613 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700614 } else { // create RX path audio patch
Francois Gaffie06e324a2020-10-14 18:02:07 +0200615 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800616 // If the TX device is on the primary HW module but RX device is
617 // on other HW module, SinkMetaData of telephony input should handle it
618 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700619 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700620 if (createTxPatch) { // create TX path audio patch
François Gaffiead447b72019-11-18 15:50:22 +0100621 // terminate active capture if on the same HW module as the call TX source device
622 // FIXME: would be better to refine to only inputs whose profile connects to the
623 // call TX device but this information is not in the audio patch and logic here must be
624 // symmetric to the one in startInput()
625 for (const auto& activeDesc : mInputs.getActiveInputs()) {
626 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
627 closeActiveClients(activeDesc);
628 }
629 }
François Gaffie9eb18552018-11-05 10:33:26 +0100630 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800631 }
Francois Gaffie9da281d2021-02-04 17:02:59 +0100632 if (waitMs != nullptr) {
633 *waitMs = muteWaitMs;
634 }
635 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800636}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700637
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800638sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100639 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700640 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700641
François Gaffie11d30102018-11-02 16:09:09 +0100642 if (device == nullptr) {
643 return nullptr;
644 }
François Gaffiead447b72019-11-18 15:50:22 +0100645
François Gaffieafd4cea2019-11-18 15:50:22 +0100646 // @TODO: still ignoring the address, or not dealing platform with multiple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800647 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100648 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800649 addSource(mAvailableInputDevices.getDevice(
650 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800651 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100652 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800653 addSink(mAvailableOutputDevices.getDevice(
654 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800655 }
656
François Gaffiead447b72019-11-18 15:50:22 +0100657 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
658 status_t status =
659 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
660 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
661 if (status != NO_ERROR || index < 0) {
662 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
663 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800664 }
François Gaffiead447b72019-11-18 15:50:22 +0100665 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800666}
667
Mikhail Naganov100f0122018-11-29 11:22:16 -0800668bool AudioPolicyManager::isDeviceOfModule(
669 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
670 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
671 if (module != 0) {
672 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
673 .indexOf(devDesc) != NAME_NOT_FOUND
674 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
675 .indexOf(devDesc) != NAME_NOT_FOUND;
676 }
677 return false;
678}
679
Francois Gaffie06e324a2020-10-14 18:02:07 +0200680void AudioPolicyManager::connectTelephonyRxAudioSource()
681{
682 disconnectTelephonyRxAudioSource();
683 const struct audio_port_config source = {
684 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
685 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
686 };
687 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
688 status_t status = startAudioSource(&source, &aa, &mCallRxSourceClientPort, 0/*uid*/);
689 ALOGE_IF(status != NO_ERROR, "%s failed to start Telephony Rx AudioSource", __func__);
690}
691
692void AudioPolicyManager::disconnectTelephonyRxAudioSource()
693{
694 stopAudioSource(mCallRxSourceClientPort);
695 mCallRxSourceClientPort = AUDIO_PORT_HANDLE_NONE;
696}
697
Eric Laurente0720872014-03-11 09:30:41 -0700698void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700699{
700 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100701 // store previous phone state for management of sonification strategy below
702 int oldState = mEngine->getPhoneState();
703
704 if (mEngine->setPhoneState(state) != NO_ERROR) {
705 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700706 return;
707 }
François Gaffie2110e042015-03-24 08:41:51 +0100708 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700709 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700710 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700711 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800712 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700713 }
714
François Gaffie2110e042015-03-24 08:41:51 +0100715 /**
716 * Switching to or from incall state or switching between telephony and VoIP lead to force
717 * routing command.
718 */
Eric Laurent74b71512019-11-06 17:21:57 -0800719 bool force = ((isStateInCall(oldState) != isStateInCall(state))
720 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700721
722 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700723 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700724
Eric Laurente552edb2014-03-10 17:42:56 -0700725 int delayMs = 0;
726 if (isStateInCall(state)) {
727 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100728 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
729 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700730 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700731 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700732 // mute media and sonification strategies and delay device switch by the largest
733 // latency of any output where either strategy is active.
734 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100735 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
736 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
737 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700738 (delayMs < (int)desc->latency()*2)) {
739 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700740 }
François Gaffiec005e562018-11-06 15:04:49 +0100741 setStrategyMute(musicStrategy, true, desc);
742 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
743 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
744 nullptr, true /*fromCache*/).types());
745 setStrategyMute(sonificationStrategy, true, desc);
746 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
747 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
748 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700749 }
750 }
751
Eric Laurent87ffa392015-05-22 10:32:38 -0700752 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700753 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie9da281d2021-02-04 17:02:59 +0100754 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700755 } else {
Francois Gaffie9da281d2021-02-04 17:02:59 +0100756 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
757 // force routing command to audio hardware when ending call
758 // even if no device change is needed
759 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
760 rxDevices = mPrimaryOutput->devices();
761 }
762 if (oldState == AUDIO_MODE_IN_CALL) {
763 disconnectTelephonyRxAudioSource();
764 if (mCallTxPatch != 0) {
765 releaseAudioPatchInternal(mCallTxPatch->getHandle());
766 mCallTxPatch.clear();
767 }
768 }
François Gaffie11d30102018-11-02 16:09:09 +0100769 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700770 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700771 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700772
773 // reevaluate routing on all outputs in case tracks have been started during the call
774 for (size_t i = 0; i < mOutputs.size(); i++) {
775 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100776 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700777 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100778 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700779 }
780 }
781
Eric Laurente552edb2014-03-10 17:42:56 -0700782 if (isStateInCall(state)) {
783 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700784 // force reevaluating accessibility routing when call starts
785 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700786 }
787
788 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100789 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
790 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700791}
792
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700793audio_mode_t AudioPolicyManager::getPhoneState() {
794 return mEngine->getPhoneState();
795}
796
Eric Laurente0720872014-03-11 09:30:41 -0700797void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100798 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700799{
François Gaffie2110e042015-03-24 08:41:51 +0100800 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700801 if (config == mEngine->getForceUse(usage)) {
802 return;
803 }
Eric Laurente552edb2014-03-10 17:42:56 -0700804
François Gaffie2110e042015-03-24 08:41:51 +0100805 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
806 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
807 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700808 }
François Gaffie2110e042015-03-24 08:41:51 +0100809 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
810 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
811 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700812
813 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700814 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800815
Eric Laurent22fcda22019-05-17 16:28:47 -0700816 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
817 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
818 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
819 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
820 }
821
Eric Laurentdc462862016-07-19 12:29:53 -0700822 //FIXME: workaround for truncated touch sounds
823 // to be removed when the problem is handled by system UI
824 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700825 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
826 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
827 }
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -0700828
829 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurentcca11ce2020-11-25 15:31:27 +0100830 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700831}
832
Eric Laurente0720872014-03-11 09:30:41 -0700833void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700834{
835 ALOGV("setSystemProperty() property %s, value %s", property, value);
836}
837
Michael Chana94fbb22018-04-24 14:31:19 +1000838// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
839// search to profiles for direct outputs.
840sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100841 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000842 uint32_t samplingRate,
843 audio_format_t format,
844 audio_channel_mask_t channelMask,
845 audio_output_flags_t flags,
846 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700847{
Michael Chana94fbb22018-04-24 14:31:19 +1000848 if (directOnly) {
849 // only retain flags that will drive the direct output profile selection
850 // if explicitly requested
851 static const uint32_t kRelevantFlags =
852 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lata97a47182019-07-03 11:15:33 -0700853 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000854 flags =
855 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
856 }
Eric Laurent861a6282015-05-18 15:40:16 -0700857
858 sp<IOProfile> profile;
859
Mikhail Naganovd4120142017-12-06 15:49:22 -0800860 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800861 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100862 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700863 samplingRate, NULL /*updatedSamplingRate*/,
864 format, NULL /*updatedFormat*/,
865 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700866 flags)) {
867 continue;
868 }
869 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100870 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700871 continue;
872 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800873 // reject profiles if connected device does not support codec
jiabin12dc6b02019-10-01 09:38:30 -0700874 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800875 continue;
876 }
Michael Chana94fbb22018-04-24 14:31:19 +1000877 if (!directOnly) return curProfile;
878 // when searching for direct outputs, if several profiles are compatible, give priority
879 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100880 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700881 continue;
882 }
883 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100884 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700885 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700886 }
Eric Laurente552edb2014-03-10 17:42:56 -0700887 }
888 }
Eric Laurent861a6282015-05-18 15:40:16 -0700889 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700890}
891
Eric Laurentf4e63452017-11-06 19:31:46 +0000892audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700893{
François Gaffiec005e562018-11-06 15:04:49 +0100894 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800895
896 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
897 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
898 // format, flags, etc. This may result in some discrepancy for functions that utilize
899 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
900 // and AudioSystem::getOutputSamplingRate().
901
François Gaffie11d30102018-11-02 16:09:09 +0100902 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700903 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700904
François Gaffie11d30102018-11-02 16:09:09 +0100905 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
906 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000907 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700908}
909
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700910status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
911 const audio_attributes_t *srcAttr,
912 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700913{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700914 if (srcAttr != NULL) {
915 if (!isValidAttributes(srcAttr)) {
916 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
917 __func__,
918 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
919 srcAttr->tags);
920 return BAD_VALUE;
921 }
922 *dstAttr = *srcAttr;
923 } else {
924 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
925 ALOGE("%s: invalid stream type", __func__);
926 return BAD_VALUE;
927 }
François Gaffiec005e562018-11-06 15:04:49 +0100928 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700929 }
Eric Laurent22fcda22019-05-17 16:28:47 -0700930
931 // Only honor audibility enforced when required. The client will be
932 // forced to reconnect if the forced usage changes.
933 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganove3b59ac2020-10-01 15:08:13 -0700934 dstAttr->flags = static_cast<audio_flags_mask_t>(
935 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -0700936 }
937
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700938 return NO_ERROR;
939}
940
Kevin Rocard153f92d2018-12-18 18:33:28 -0800941status_t AudioPolicyManager::getOutputForAttrInt(
942 audio_attributes_t *resultAttr,
943 audio_io_handle_t *output,
944 audio_session_t session,
945 const audio_attributes_t *attr,
946 audio_stream_type_t *stream,
947 uid_t uid,
948 const audio_config_t *config,
949 audio_output_flags_t *flags,
950 audio_port_handle_t *selectedDeviceId,
951 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -0700952 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -0800953 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700954{
François Gaffiec005e562018-11-06 15:04:49 +0100955 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +0100956 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100957 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +0100958 const sp<DeviceDescriptor> requestedDevice =
959 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
960
Eric Laurent8a1095a2019-11-08 14:44:16 -0800961 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700962 status_t status = getAudioAttributes(resultAttr, attr, *stream);
963 if (status != NO_ERROR) {
964 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700965 }
Kevin Rocardb99cc752019-03-21 20:52:24 -0700966 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganove3b59ac2020-10-01 15:08:13 -0700967 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -0700968 }
François Gaffiec005e562018-11-06 15:04:49 +0100969 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -0700970
François Gaffiec005e562018-11-06 15:04:49 +0100971 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
972 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700973
Kevin Rocard153f92d2018-12-18 18:33:28 -0800974 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
975 // otherwise, fallback to the dynamic policies, if none match, query the engine.
976 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -0700977 sp<AudioPolicyMix> primaryMix;
978 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -0700979 if (status != OK) {
980 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800981 }
Kevin Rocard94114a22019-04-01 19:38:23 -0700982
Kevin Rocard153f92d2018-12-18 18:33:28 -0800983 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -0700984 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800985
986 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -0700987 if ((usePrimaryOutputFromPolicyMixes
988 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -0800989 && !audio_is_linear_pcm(config->format)) {
990 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800991 return BAD_VALUE;
992 }
993 if (usePrimaryOutputFromPolicyMixes) {
François Gaffiec005e562018-11-06 15:04:49 +0100994 sp<DeviceDescriptor> deviceDesc =
Eric Laurentc529cf62020-04-17 18:19:10 -0700995 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
996 primaryMix->mDeviceAddress,
François Gaffiec005e562018-11-06 15:04:49 +0100997 AUDIO_FORMAT_DEFAULT);
Eric Laurentc529cf62020-04-17 18:19:10 -0700998 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -0700999 if (deviceDesc != nullptr
1000 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001001 audio_io_handle_t newOutput;
1002 status = openDirectOutput(
1003 *stream, session, config,
1004 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1005 DeviceVector(deviceDesc), &newOutput);
1006 if (status != NO_ERROR) {
1007 policyDesc = nullptr;
1008 } else {
1009 policyDesc = mOutputs.valueFor(newOutput);
1010 primaryMix->setOutput(policyDesc);
1011 }
1012 }
1013 if (policyDesc != nullptr) {
1014 policyDesc->mPolicyMix = primaryMix;
1015 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001016 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001017
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001018 ALOGV("getOutputForAttr() returns output %d", *output);
1019 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1020 *outputType = API_OUT_MIX_PLAYBACK;
1021 } else {
1022 *outputType = API_OUTPUT_LEGACY;
1023 }
1024 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001025 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001026 }
François Gaffiec005e562018-11-06 15:04:49 +01001027 // Virtual sources must always be dynamicaly or explicitly routed
1028 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1029 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1030 return BAD_VALUE;
1031 }
1032 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1033 // in order to let the choice of the order to future vendor engine
1034 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001035
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001036 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001037 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001038 }
1039
Nadav Barb2f18162018-07-18 13:01:53 +03001040 // Set incall music only if device was explicitly set, and fallback to the device which is
1041 // chosen by the engine if not.
1042 // FIXME: provide a more generic approach which is not device specific and move this back
1043 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001044 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin12dc6b02019-10-01 09:38:30 -07001045 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001046 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001047 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001048 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001049 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001050 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001051 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001052 }
1053 }
1054
François Gaffiec005e562018-11-06 15:04:49 +01001055 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1056 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1057 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001058
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001059 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001060 if (!msdDevices.isEmpty()) {
1061 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001062 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001063 ALOGV("%s() Using MSD devices %s instead of devices %s",
1064 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001065 } else {
1066 *output = AUDIO_IO_HANDLE_NONE;
1067 }
1068 }
1069 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabine375d412019-02-26 12:54:53 -08001070 *output = getOutputForDevices(outputDevices, session, *stream, config,
Eric Laurent42984412019-05-09 17:57:03 -07001071 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001072 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001073 if (*output == AUDIO_IO_HANDLE_NONE) {
1074 return INVALID_OPERATION;
1075 }
Paul McLeanaa981192015-03-21 09:55:15 -07001076
François Gaffiec005e562018-11-06 15:04:49 +01001077 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chanb7637e92020-12-08 15:44:49 +11001078 for (auto &outputDevice : outputDevices) {
1079 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1080 *selectedDeviceId = outputDevice->getId();
1081 break;
1082 }
1083 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001084
Eric Laurent8a1095a2019-11-08 14:44:16 -08001085 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1086 *outputType = API_OUTPUT_TELEPHONY_TX;
1087 } else {
1088 *outputType = API_OUTPUT_LEGACY;
1089 }
1090
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001091 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1092
1093 return NO_ERROR;
1094}
1095
1096status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1097 audio_io_handle_t *output,
1098 audio_session_t session,
1099 audio_stream_type_t *stream,
1100 uid_t uid,
1101 const audio_config_t *config,
1102 audio_output_flags_t *flags,
1103 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001104 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001105 std::vector<audio_io_handle_t> *secondaryOutputs,
1106 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001107{
1108 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1109 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1110 return INVALID_OPERATION;
1111 }
Francois Gaffie716e1432019-01-14 16:58:59 +01001112 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001113 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001114 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001115 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001116 const sp<DeviceDescriptor> requestedDevice =
1117 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1118
1119 // Prevent from storing invalid requested device id in clients
1120 const audio_port_handle_t sanitizedRequestedPortId =
1121 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1122 *selectedDeviceId = sanitizedRequestedPortId;
1123
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001124 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001125 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001126 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001127 if (status != NO_ERROR) {
1128 return status;
1129 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001130 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001131 if (secondaryOutputs != nullptr) {
1132 for (auto &secondaryMix : secondaryMixes) {
1133 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1134 if (outputDesc != nullptr &&
1135 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1136 secondaryOutputs->push_back(outputDesc->mIoHandle);
1137 weakSecondaryOutputDescs.push_back(outputDesc);
1138 }
1139 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001140 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001141
Eric Laurent8fc147b2018-07-22 19:13:55 -07001142 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulnierscb137d02019-10-15 18:30:45 -07001143 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001144 .format = config->format,
Nick Desaulnierscb137d02019-10-15 18:30:45 -07001145 };
jiabindff2a4f2019-09-10 14:29:54 -07001146 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001147
Eric Laurentc209fe42020-06-05 18:11:23 -07001148 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001149 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001150 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001151 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001152 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001153 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001154 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001155 std::move(weakSecondaryOutputDescs),
1156 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001157 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001158
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001159 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1160 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001161
Eric Laurente83b55d2014-11-14 10:06:21 -08001162 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001163}
1164
Eric Laurentc529cf62020-04-17 18:19:10 -07001165status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1166 audio_session_t session,
1167 const audio_config_t *config,
1168 audio_output_flags_t flags,
1169 const DeviceVector &devices,
1170 audio_io_handle_t *output) {
1171
1172 *output = AUDIO_IO_HANDLE_NONE;
1173
1174 // skip direct output selection if the request can obviously be attached to a mixed output
1175 // and not explicitly requested
1176 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1177 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1178 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1179 return NAME_NOT_FOUND;
1180 }
1181
1182 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1183 // This prevents creating an offloaded track and tearing it down immediately after start
1184 // when audioflinger detects there is an active non offloadable effect.
1185 // FIXME: We should check the audio session here but we do not have it in this context.
1186 // This may prevent offloading in rare situations where effects are left active by apps
1187 // in the background.
1188 sp<IOProfile> profile;
1189 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1190 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1191 profile = getProfileForOutput(
1192 devices, config->sample_rate, config->format, config->channel_mask,
1193 flags, true /* directOnly */);
1194 }
1195
1196 if (profile == nullptr) {
1197 return NAME_NOT_FOUND;
1198 }
1199
1200 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1201 for (size_t i = 0; i < mOutputs.size(); i++) {
1202 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1203 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1204 // reuse direct output if currently open by the same client
1205 // and configured with same parameters
1206 if ((config->sample_rate == desc->getSamplingRate()) &&
1207 (config->format == desc->getFormat()) &&
1208 (config->channel_mask == desc->getChannelMask()) &&
1209 (session == desc->mDirectClientSession)) {
1210 desc->mDirectOpenCount++;
1211 ALOGI("%s reusing direct output %d for session %d", __func__,
1212 mOutputs.keyAt(i), session);
1213 *output = mOutputs.keyAt(i);
1214 return NO_ERROR;
1215 }
1216 }
1217 }
1218
1219 if (!profile->canOpenNewIo()) {
1220 return NAME_NOT_FOUND;
1221 }
1222
1223 sp<SwAudioOutputDescriptor> outputDesc =
1224 new SwAudioOutputDescriptor(profile, mpClientInterface);
1225
Michael Chanb7637e92020-12-08 15:44:49 +11001226 // An MSD patch may be using the only output stream that can service this request. Release
1227 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001228 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001229
1230 status_t status = outputDesc->open(config, devices, stream, flags, output);
1231
1232 // only accept an output with the requested parameters
1233 if (status != NO_ERROR ||
1234 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1235 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1236 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1237 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1238 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1239 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1240 config->channel_mask, outputDesc->getChannelMask());
1241 if (*output != AUDIO_IO_HANDLE_NONE) {
1242 outputDesc->close();
1243 }
1244 // fall back to mixer output if possible when the direct output could not be open
1245 if (audio_is_linear_pcm(config->format) &&
1246 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1247 return NAME_NOT_FOUND;
1248 }
1249 *output = AUDIO_IO_HANDLE_NONE;
1250 return BAD_VALUE;
1251 }
1252 outputDesc->mDirectOpenCount = 1;
1253 outputDesc->mDirectClientSession = session;
1254
1255 addOutput(*output, outputDesc);
1256 mPreviousOutputs = mOutputs;
1257 ALOGV("%s returns new direct output %d", __func__, *output);
1258 mpClientInterface->onAudioPortListUpdate();
1259 return NO_ERROR;
1260}
1261
François Gaffie11d30102018-11-02 16:09:09 +01001262audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1263 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001264 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001265 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001266 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001267 audio_output_flags_t *flags,
1268 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001269{
Andy Hungc88b0642018-04-27 15:42:35 -07001270 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001271
jiabine375d412019-02-26 12:54:53 -08001272 // Discard haptic channel mask when forcing muting haptic channels.
1273 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganove3b59ac2020-10-01 15:08:13 -07001274 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1275 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001276
Eric Laurente552edb2014-03-10 17:42:56 -07001277 // open a direct output if required by specified parameters
1278 //force direct flag if offload flag is set: offloading implies a direct output stream
1279 // and all common behaviors are driven by checking only the direct flag
1280 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001281 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1282 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001283 }
Nadav Bar766fb022018-01-07 12:18:03 +02001284 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1285 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001286 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001287 // only allow deep buffering for music stream type
1288 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001289 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001290 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001291 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001292 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1293 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001294 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001295 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001296 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001297 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001298 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001299 audio_is_linear_pcm(config->format) &&
1300 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001301 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001302 AUDIO_OUTPUT_FLAG_DIRECT);
1303 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001304 }
Eric Laurente552edb2014-03-10 17:42:56 -07001305
Eric Laurentc529cf62020-04-17 18:19:10 -07001306 audio_config_t directConfig = *config;
1307 directConfig.channel_mask = channelMask;
1308 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1309 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001310 return output;
1311 }
1312
Eric Laurent14cbfca2016-03-17 09:42:16 -07001313 // A request for HW A/V sync cannot fallback to a mixed output because time
1314 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001315 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001316 return AUDIO_IO_HANDLE_NONE;
1317 }
1318
Eric Laurente552edb2014-03-10 17:42:56 -07001319 // ignoring channel mask due to downmix capability in mixer
1320
1321 // open a non direct output
1322
1323 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001324 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001325 // get which output is suitable for the specified stream. The actual
1326 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001327 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001328
Eric Laurent8838a382014-09-08 16:44:28 -07001329 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001330 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabine375d412019-02-26 12:54:53 -08001331 output = selectOutput(outputs, *flags, config->format, channelMask, config->sample_rate);
Eric Laurente552edb2014-03-10 17:42:56 -07001332 }
François Gaffie11d30102018-11-02 16:09:09 +01001333 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001334 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001335 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001336
Eric Laurente552edb2014-03-10 17:42:56 -07001337 return output;
1338}
1339
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001340sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001341 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1342 mAvailableInputDevices);
1343 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1344}
1345
1346DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1347 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1348 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001349}
1350
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001351const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001352 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001353 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1354 if (msdModule != 0) {
1355 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1356 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1357 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1358 const struct audio_port_config *source = &patch->mPatch.sources[j];
1359 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1360 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffiead447b72019-11-18 15:50:22 +01001361 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001362 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001363 }
1364 }
1365 }
1366 return msdPatches;
1367}
1368
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001369status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1370 const InputProfileCollection &inputProfiles,
1371 const OutputProfileCollection &outputProfiles,
1372 const sp<DeviceDescriptor> &sourceDevice,
1373 const sp<DeviceDescriptor> &sinkDevice,
1374 AudioProfileVector& sourceProfiles,
1375 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001376 if (inputProfiles.isEmpty()) {
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001377 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001378 return NO_INIT;
1379 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001380 if (outputProfiles.isEmpty()) {
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001381 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001382 return NO_INIT;
1383 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001384 for (const auto &inProfile : inputProfiles) {
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001385 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1386 inProfile->supportsDevice(sourceDevice)) {
1387 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001388 }
1389 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001390 for (const auto &outProfile : outputProfiles) {
Michael Chanb7637e92020-12-08 15:44:49 +11001391 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001392 outProfile->supportsDevice(sinkDevice)) {
1393 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001394 }
1395 }
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001396 return NO_ERROR;
1397}
1398
1399status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1400 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1401 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1402{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001403 struct audio_config_base bestSinkConfig;
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001404 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1405 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1406 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001407 if (result != NO_ERROR) {
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001408 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1409 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001410 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001411 }
1412 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1413 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1414 sinkConfig->format = bestSinkConfig.format;
1415 // For encoded streams force direct flag to prevent downstream mixing.
1416 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1417 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001418 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1419 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001420 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001421 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1422 // raw and IEC61937 framed streams.
1423 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1424 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1425 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001426 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1427 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1428 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1429 sourceConfig->format = bestSinkConfig.format;
1430 // Copy input stream directly without any processing (e.g. resampling).
1431 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1432 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1433 if (hwAvSync) {
1434 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1435 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1436 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1437 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1438 }
1439 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1440 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1441 sinkConfig->config_mask |= config_mask;
1442 sourceConfig->config_mask |= config_mask;
1443 return NO_ERROR;
1444}
1445
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001446PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1447 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001448{
1449 PatchBuilder patchBuilder;
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001450 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1451 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1452 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1453 if (deviceModule == nullptr) {
1454 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1455 return patchBuilder;
1456 }
1457 const InputProfileCollection inputProfiles = msdIsSource ?
1458 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1459 const OutputProfileCollection outputProfiles = msdIsSource ?
1460 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1461
1462 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1463 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1464 device : getMsdAudioOutDevices().itemAt(0);
1465 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1466
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001467 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1468 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001469 AudioProfileVector sourceProfiles;
1470 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001471 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1472 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001473 for (auto hwAvSync : { true, false }) {
1474 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1475 sourceProfiles, sinkProfiles) != NO_ERROR) {
1476 continue;
1477 }
1478 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1479 &sinkConfig) == NO_ERROR) {
1480 // Found a matching config. Re-create PatchBuilder with this config.
1481 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1482 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001483 }
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001484 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001485 " supporting PCM format conversion.", __func__);
1486 return patchBuilder;
1487}
1488
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001489status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chanb7637e92020-12-08 15:44:49 +11001490 DeviceVector devices;
1491 if (outputDevices != nullptr && outputDevices->size() > 0) {
1492 devices.add(*outputDevices);
1493 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001494 // Use media strategy for unspecified output device. This should only
1495 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1496 // therefore invalidate explicit routing requests.
Michael Chanb7637e92020-12-08 15:44:49 +11001497 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001498 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chanb7637e92020-12-08 15:44:49 +11001499 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001500 }
Michael Chanb7637e92020-12-08 15:44:49 +11001501 std::vector<PatchBuilder> patchesToCreate;
1502 for (auto i = 0u; i < devices.size(); ++i) {
1503 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001504 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chanb7637e92020-12-08 15:44:49 +11001505 }
1506 // Retain only the MSD patches associated with outputDevices request.
1507 // Tear down the others, and create new ones as needed.
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001508 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chanb7637e92020-12-08 15:44:49 +11001509 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1510 auto retainedPatch = false;
1511 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1512 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1513 patchesToRemove.removeItemsAt(i);
1514 retainedPatch = true;
1515 break;
1516 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001517 }
Michael Chanb7637e92020-12-08 15:44:49 +11001518 if (retainedPatch) {
1519 it = patchesToCreate.erase(it);
1520 continue;
1521 }
1522 ++it;
1523 }
1524 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1525 return NO_ERROR;
1526 }
1527 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1528 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffiead447b72019-11-18 15:50:22 +01001529 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001530 }
Michael Chanb7637e92020-12-08 15:44:49 +11001531 status_t status = NO_ERROR;
1532 for (const auto &p : patchesToCreate) {
1533 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1534 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1535 char message[256];
1536 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1537 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1538 currStatus == NO_ERROR ? "Success" : "Error",
1539 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1540 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1541 if (currStatus == NO_ERROR) {
1542 ALOGD("%s", message);
1543 } else {
1544 ALOGE("%s", message);
1545 if (status == NO_ERROR) {
1546 status = currStatus;
1547 }
1548 }
1549 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001550 return status;
1551}
1552
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11001553void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1554 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chanb7637e92020-12-08 15:44:49 +11001555 for (size_t i = 0; i < msdPatches.size(); i++) {
1556 const auto& patch = msdPatches[i];
1557 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1558 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1559 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1560 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1561 releaseAudioPatch(patch->getHandle(), mUidCached);
1562 break;
1563 }
1564 }
1565 }
1566}
1567
Eric Laurente0720872014-03-11 09:30:41 -07001568audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001569 audio_output_flags_t flags,
jiabin40573322018-11-08 12:08:02 -08001570 audio_format_t format,
1571 audio_channel_mask_t channelMask,
1572 uint32_t samplingRate)
Eric Laurente552edb2014-03-10 17:42:56 -07001573{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001574 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1575 "%s called with format %#x", __func__, format);
1576
1577 // Flags disqualifying an output: the match must happen before calling selectOutput()
1578 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1579 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1580
1581 // Flags expressing a functional request: must be honored in priority over
1582 // other criteria
1583 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1584 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1585 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1586 // Flags expressing a performance request: have lower priority than serving
1587 // requested sampling rate or channel mask
1588 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1589 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1590 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1591
1592 const audio_output_flags_t functionalFlags =
1593 (audio_output_flags_t)(flags & kFunctionalFlags);
1594 const audio_output_flags_t performanceFlags =
1595 (audio_output_flags_t)(flags & kPerformanceFlags);
1596
1597 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1598
Eric Laurente552edb2014-03-10 17:42:56 -07001599 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001600 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001601 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001602 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001603 // 2: the output with the highest number of requested functional flags
1604 // 3: the output supporting the exact channel mask
1605 // 4: the output with a higher channel count than requested
1606 // 5: the output with a higher sampling rate than requested
1607 // 6: the output with the highest number of requested performance flags
1608 // 7: the output with the bit depth the closest to the requested one
1609 // 8: the primary output
1610 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001611
Eric Laurent16c66dd2019-05-01 17:54:10 -07001612 // matching criteria values in priority order for best matching output so far
1613 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001614
Eric Laurent16c66dd2019-05-01 17:54:10 -07001615 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1616 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1617 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001618
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001619 for (audio_io_handle_t output : outputs) {
1620 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001621 // matching criteria values in priority order for current output
1622 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001623
Eric Laurent16c66dd2019-05-01 17:54:10 -07001624 if (outputDesc->isDuplicated()) {
1625 continue;
1626 }
1627 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1628 continue;
1629 }
Eric Laurent8838a382014-09-08 16:44:28 -07001630
Eric Laurent16c66dd2019-05-01 17:54:10 -07001631 // If haptic channel is specified, use the haptic output if present.
1632 // When using haptic output, same audio format and sample rate are required.
1633 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabineaf09f02019-08-19 15:08:30 -07001634 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001635 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1636 continue;
1637 }
1638 if (outputHapticChannelCount >= hapticChannelCount
jiabineaf09f02019-08-19 15:08:30 -07001639 && format == outputDesc->getFormat()
1640 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001641 currentMatchCriteria[0] = outputHapticChannelCount;
1642 }
1643
1644 // functional flags match
1645 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1646
1647 // channel mask and channel count match
jiabineaf09f02019-08-19 15:08:30 -07001648 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1649 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001650 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1651 channelCount <= outputChannelCount) {
1652 if ((audio_channel_mask_get_representation(channelMask) ==
jiabineaf09f02019-08-19 15:08:30 -07001653 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1654 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001655 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001656 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001657 currentMatchCriteria[3] = outputChannelCount;
1658 }
1659
1660 // sampling rate match
1661 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabineaf09f02019-08-19 15:08:30 -07001662 samplingRate <= outputDesc->getSamplingRate()) {
1663 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001664 }
1665
1666 // performance flags match
1667 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1668
1669 // format match
1670 if (format != AUDIO_FORMAT_INVALID) {
1671 currentMatchCriteria[6] =
jiabindff2a4f2019-09-10 14:29:54 -07001672 PolicyAudioPort::kFormatDistanceMax -
1673 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001674 }
1675
1676 // primary output match
1677 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1678
1679 // compare match criteria by priority then value
1680 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1681 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1682 bestMatchCriteria = currentMatchCriteria;
1683 bestOutput = output;
1684
1685 std::stringstream result;
1686 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1687 std::ostream_iterator<int>(result, " "));
1688 ALOGV("%s new bestOutput %d criteria %s",
1689 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001690 }
1691 }
1692
Eric Laurent16c66dd2019-05-01 17:54:10 -07001693 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001694}
1695
Eric Laurent8fc147b2018-07-22 19:13:55 -07001696status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001697{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001698 ALOGV("%s portId %d", __FUNCTION__, portId);
1699
1700 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1701 if (outputDesc == 0) {
1702 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001703 return BAD_VALUE;
1704 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001705 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001706
Eric Laurent8fc147b2018-07-22 19:13:55 -07001707 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001708 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001709
Eric Laurent733ce942017-12-07 12:18:25 -08001710 status_t status = outputDesc->start();
1711 if (status != NO_ERROR) {
1712 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001713 }
1714
Eric Laurent97ac8712018-07-27 18:59:02 -07001715 uint32_t delayMs;
1716 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001717
1718 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001719 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001720 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001721 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001722 if (delayMs != 0) {
1723 usleep(delayMs * 1000);
1724 }
1725
1726 return status;
1727}
1728
Eric Laurent97ac8712018-07-27 18:59:02 -07001729status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1730 const sp<TrackClientDescriptor>& client,
1731 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001732{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001733 // cannot start playback of STREAM_TTS if any other output is being used
1734 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001735
1736 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001737 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001738 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001739 auto clientStrategy = client->strategy();
1740 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001741 if (stream == AUDIO_STREAM_TTS) {
1742 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001743 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001744 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001745 return INVALID_OPERATION;
1746 } else {
1747 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1748 }
1749 } else {
1750 // some playback other than beacon starts
1751 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1752 }
1753
Eric Laurent77305a62016-07-25 16:39:22 -07001754 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001755 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001756 bool force = !outputDesc->isActive() &&
1757 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001758
François Gaffie11d30102018-11-02 16:09:09 +01001759 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001760 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001761 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001762 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001763 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001764 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001765 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001766 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001767 } else {
1768 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001769 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001770 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1771 AUDIO_FORMAT_DEFAULT);
1772 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1773 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001774 }
1775
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001776 // requiresMuteCheck is false when we can bypass mute strategy.
1777 // It covers a common case when there is no materially active audio
1778 // and muting would result in unnecessary delay and dropped audio.
1779 const uint32_t outputLatencyMs = outputDesc->latency();
1780 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1781
Eric Laurente552edb2014-03-10 17:42:56 -07001782 // increment usage count for this stream on the requested output:
1783 // NOTE that the usage count is the same for duplicated output and hardware output which is
1784 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001785 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001786
1787 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001788 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1789 client->isPreferredDeviceForExclusiveUse()) {
1790 // Preferred device may be exclusive, use only if no other active clients on this output
1791 devices = DeviceVector(
1792 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1793 } else {
1794 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1795 }
François Gaffie11d30102018-11-02 16:09:09 +01001796 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001797 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001798 }
1799 }
Eric Laurente552edb2014-03-10 17:42:56 -07001800
François Gaffiec005e562018-11-06 15:04:49 +01001801 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001802 selectOutputForMusicEffects();
1803 }
1804
François Gaffie1c878552018-11-22 16:53:21 +01001805 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001806 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001807 if (devices.isEmpty()) {
1808 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001809 }
François Gaffiec005e562018-11-06 15:04:49 +01001810 bool shouldWait =
1811 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1812 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1813 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001814 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001815 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001816 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001817 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001818 // An output has a shared device if
1819 // - managed by the same hw module
1820 // - supports the currently selected device
1821 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001822 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001823
Eric Laurent77305a62016-07-25 16:39:22 -07001824 // force a device change if any other output is:
1825 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001826 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001827 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001828 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001829 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001830 // change the device currently selected by the other output.
1831 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001832 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001833 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001834 force = true;
1835 }
1836 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001837 // a notification so that audio focus effect can propagate, or that a mute/unmute
1838 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001839 const uint32_t latencyMs = desc->latency();
1840 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1841
1842 if (shouldWait && isActive && (waitMs < latencyMs)) {
1843 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001844 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001845
1846 // Require mute check if another output is on a shared device
1847 // and currently active to have proper drain and avoid pops.
1848 // Note restoring AudioTracks onto this output needs to invoke
1849 // a volume ramp if there is no mute.
1850 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001851 }
1852 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001853
1854 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001855 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001856
Eric Laurente552edb2014-03-10 17:42:56 -07001857 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001858 auto &curves = getVolumeCurves(client->attributes());
1859 checkAndSetVolume(curves, client->volumeSource(),
1860 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001861 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001862 outputDesc->devices().types(), 0 /*delay*/,
1863 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001864
1865 // update the outputs if starting an output with a stream that can affect notification
1866 // routing
1867 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001868
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001869 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001870 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001871 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1872 }
Eric Laurentdc462862016-07-19 12:29:53 -07001873
1874 if (waitMs > muteWaitMs) {
1875 *delayMs = waitMs - muteWaitMs;
1876 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001877
1878 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1879 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1880 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1881 // change occurs after the MixerThread starts and causes a stream volume
1882 // glitch.
1883 //
1884 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001885 }
Eric Laurentdc462862016-07-19 12:29:53 -07001886
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001887 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin12dc6b02019-10-01 09:38:30 -07001888 mEngine->getForceUse(
1889 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001890 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001891 }
1892
Eric Laurent97ac8712018-07-27 18:59:02 -07001893 // Automatically enable the remote submix input when output is started on a re routing mix
1894 // of type MIX_TYPE_RECORDERS
jiabin12dc6b02019-10-01 09:38:30 -07001895 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1896 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001897 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1898 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1899 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001900 "remote-submix",
1901 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001902 }
1903
Eric Laurente552edb2014-03-10 17:42:56 -07001904 return NO_ERROR;
1905}
1906
Eric Laurent8fc147b2018-07-22 19:13:55 -07001907status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001908{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001909 ALOGV("%s portId %d", __FUNCTION__, portId);
1910
1911 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1912 if (outputDesc == 0) {
1913 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001914 return BAD_VALUE;
1915 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001916 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001917
Eric Laurent97ac8712018-07-27 18:59:02 -07001918 ALOGV("stopOutput() output %d, stream %d, session %d",
1919 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001920
Eric Laurent97ac8712018-07-27 18:59:02 -07001921 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001922
Eric Laurent733ce942017-12-07 12:18:25 -08001923 if (status == NO_ERROR ) {
1924 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001925 }
1926 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001927}
1928
Eric Laurent97ac8712018-07-27 18:59:02 -07001929status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1930 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001931{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001932 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001933 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001934 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07001935
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001936 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1937
François Gaffie1c878552018-11-22 16:53:21 +01001938 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
1939 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001940 // Automatically disable the remote submix input when output is stopped on a
1941 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001942 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin12dc6b02019-10-01 09:38:30 -07001943 if (isSingleDeviceType(
1944 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001945 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001946 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001947 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1948 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001949 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001950 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001951 }
1952 }
1953 bool forceDeviceUpdate = false;
1954 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01001955 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07001956 forceDeviceUpdate = true;
1957 }
1958
Eric Laurente552edb2014-03-10 17:42:56 -07001959 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001960 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001961
Eric Laurente552edb2014-03-10 17:42:56 -07001962 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01001963 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01001964 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01001965 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001966 // delay the device switch by twice the latency because stopOutput() is executed when
1967 // the track stop() command is received and at that time the audio track buffer can
1968 // still contain data that needs to be drained. The latency only covers the audio HAL
1969 // and kernel buffers. Also the latency does not always include additional delay in the
1970 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001971 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001972
1973 // force restoring the device selection on other active outputs if it differs from the
1974 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001975 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001976 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001977 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001978 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001979 desc->isActive() &&
1980 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001981 (newDevices != desc->devices())) {
1982 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1983 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001984
François Gaffie11d30102018-11-02 16:09:09 +01001985 setOutputDevices(desc, newDevices2, force, delayMs);
1986
Eric Laurent57de36c2016-09-28 16:59:11 -07001987 // re-apply device specific volume if not done by setOutputDevice()
1988 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001989 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001990 }
Eric Laurente552edb2014-03-10 17:42:56 -07001991 }
1992 }
1993 // update the outputs if stopping one with a stream that can affect notification routing
1994 handleNotificationRoutingForStream(stream);
1995 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001996
1997 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1998 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08001999 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002000 }
2001
François Gaffiec005e562018-11-06 15:04:49 +01002002 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002003 selectOutputForMusicEffects();
2004 }
Eric Laurente552edb2014-03-10 17:42:56 -07002005 return NO_ERROR;
2006 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002007 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002008 return INVALID_OPERATION;
2009 }
2010}
2011
Eric Laurent8fc147b2018-07-22 19:13:55 -07002012void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002013{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002014 ALOGV("%s portId %d", __FUNCTION__, portId);
2015
2016 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2017 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002018 // If an output descriptor is closed due to a device routing change,
2019 // then there are race conditions with releaseOutput from tracks
2020 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2021 // destroyed shortly thereafter.
2022 //
2023 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002024 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002025 return;
2026 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002027
2028 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002029
Eric Laurent8fc147b2018-07-22 19:13:55 -07002030 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2031 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002032 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002033 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002034 return;
2035 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002036 if (--outputDesc->mDirectOpenCount == 0) {
2037 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002038 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002039 }
2040 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002041 // stopOutput() needs to be successfully called before releaseOutput()
2042 // otherwise there may be inaccurate stream reference counts.
2043 // This is checked in outputDesc->removeClient below.
2044 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002045}
2046
Eric Laurentcaf7f482014-11-25 17:50:47 -08002047status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2048 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002049 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002050 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002051 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002052 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002053 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002054 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002055 input_type_t *inputType,
2056 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002057{
François Gaffiec005e562018-11-06 15:04:49 +01002058 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
2059 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
2060 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002061
Eric Laurentad2e7b92017-09-14 20:06:42 -07002062 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002063 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002064 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002065 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002066 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002067 sp<AudioInputDescriptor> inputDesc;
2068 sp<RecordClientDescriptor> clientDesc;
2069 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002070 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002071
2072 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2073 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2074 return INVALID_OPERATION;
2075 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002076
Francois Gaffie716e1432019-01-14 16:58:59 +01002077 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2078 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002079 }
2080
Paul McLean466dc8e2015-04-17 13:15:36 -06002081 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01002082 sp<DeviceDescriptor> explicitRoutingDevice =
2083 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002084
Eric Laurentad2e7b92017-09-14 20:06:42 -07002085 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2086 // possible
2087 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2088 *input != AUDIO_IO_HANDLE_NONE) {
2089 ssize_t index = mInputs.indexOfKey(*input);
2090 if (index < 0) {
2091 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2092 status = BAD_VALUE;
2093 goto error;
2094 }
2095 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002096 RecordClientVector clients = inputDesc->getClientsForSession(session);
2097 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002098 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2099 status = BAD_VALUE;
2100 goto error;
2101 }
2102 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2103 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002104 // corresponds to a new client and is only permitted from the same UID.
2105 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002106 if (clients.size() > 1) {
2107 for (const auto& client : clients) {
2108 // The client map is ordered by key values (portId) and portIds are allocated
2109 // incrementaly. So the first client in this list is the one opened by audio flinger
2110 // when the mmap stream is created and should be ignored as it does not correspond
2111 // to an actual client
2112 if (client == *clients.cbegin()) {
2113 continue;
2114 }
2115 if (uid != client->uid() && !client->isSilenced()) {
2116 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2117 uid, client->portId(), client->uid());
2118 status = INVALID_OPERATION;
2119 goto error;
2120 }
Eric Laurent331679c2018-04-16 17:03:16 -07002121 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002122 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002123 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002124 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002125
Eric Laurent8f42ea12018-08-08 09:08:25 -07002126 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002127 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002128 }
2129
2130 *input = AUDIO_IO_HANDLE_NONE;
2131 *inputType = API_INPUT_INVALID;
2132
Francois Gaffie716e1432019-01-14 16:58:59 +01002133 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002134
Francois Gaffie716e1432019-01-14 16:58:59 +01002135 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2136 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2137 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002138 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002139 ALOGW("%s could not find input mix for attr %s",
2140 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002141 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002142 }
jiabinc1de2df2019-05-07 14:26:40 -07002143 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2144 String8(attr->tags + strlen("addr=")),
2145 AUDIO_FORMAT_DEFAULT);
2146 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002147 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002148 __func__, attributes.source, attributes.tags);
2149 status = BAD_VALUE;
2150 goto error;
2151 }
2152
Kevin Rocard25f9b052019-02-27 15:08:54 -08002153 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2154 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2155 } else {
2156 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2157 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002158 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002159 if (explicitRoutingDevice != nullptr) {
2160 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002161 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002162 // Prevent from storing invalid requested device id in clients
2163 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002164 device = mEngine->getInputDeviceForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07002165 }
François Gaffie11d30102018-11-02 16:09:09 +01002166 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002167 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002168 status = BAD_VALUE;
2169 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002170 }
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002171 if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002172 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2173 // there is an external policy, but this input is attached to a mix of recorders,
2174 // meaning it receives audio injected into the framework, so the recorder doesn't
2175 // know about it and is therefore considered "legacy"
2176 *inputType = API_INPUT_LEGACY;
2177 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002178 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002179 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002180 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002181 } else {
2182 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002183 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002184
Eric Laurent599c7582015-12-07 18:05:55 -08002185 }
2186
François Gaffiec005e562018-11-06 15:04:49 +01002187 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002188 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002189 status = INVALID_OPERATION;
2190 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002191 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002192
Eric Laurent8f42ea12018-08-08 09:08:25 -07002193exit:
2194
François Gaffiec005e562018-11-06 15:04:49 +01002195 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2196 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002197
Francois Gaffie716e1432019-01-14 16:58:59 +01002198 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002199 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabindff2a4f2019-09-10 14:29:54 -07002200 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002201
Mikhail Naganov2996f672019-04-18 12:29:59 -07002202 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002203 requestedDeviceId, attributes.source, flags,
2204 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002205 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002206 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002207
2208 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2209 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002210
Eric Laurent599c7582015-12-07 18:05:55 -08002211 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002212
2213error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002214 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002215}
2216
2217
François Gaffie11d30102018-11-02 16:09:09 +01002218audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002219 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002220 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002221 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002222 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002223 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002224{
2225 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002226 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002227 bool isSoundTrigger = false;
2228
François Gaffiec005e562018-11-06 15:04:49 +01002229 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002230 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2231 if (index >= 0) {
2232 input = mSoundTriggerSessions.valueFor(session);
2233 isSoundTrigger = true;
2234 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2235 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2236 } else {
2237 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002238 }
François Gaffiec005e562018-11-06 15:04:49 +01002239 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002240 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002241 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002242 }
2243
Andy Hungf129b032015-04-07 13:45:50 -07002244 // find a compatible input profile (not necessarily identical in parameters)
2245 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002246 // sampling rate and flags may be updated by getInputProfile
2247 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2248 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002249 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002250 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002251 audio_input_flags_t profileFlags = flags;
2252 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002253 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002254 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002255 profileFlags);
2256 if (profile != 0) {
2257 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002258 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2259 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002260 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2261 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2262 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002263 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2264 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2265 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002266 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002267 }
Eric Laurente552edb2014-03-10 17:42:56 -07002268 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002269 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002270 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002271 if (samplingRate == 0) {
2272 samplingRate = profileSamplingRate;
2273 }
Eric Laurente552edb2014-03-10 17:42:56 -07002274
Eric Laurent322b4d22015-04-03 15:57:54 -07002275 if (profile->getModuleHandle() == 0) {
2276 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002277 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002278 }
2279
Eric Laurent3974e3b2017-12-07 17:58:43 -08002280 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002281 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002282 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002283 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002284 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002285 continue;
2286 }
2287 // if sound trigger, reuse input if used by other sound trigger on same session
2288 // else
2289 // reuse input if active client app is not in IDLE state
2290 //
2291 RecordClientVector clients = desc->clientsList();
2292 bool doClose = false;
2293 for (const auto& client : clients) {
2294 if (isSoundTrigger != client->isSoundTrigger()) {
2295 continue;
2296 }
2297 if (client->isSoundTrigger()) {
2298 if (session == client->session()) {
2299 return desc->mIoHandle;
2300 }
2301 continue;
2302 }
2303 if (client->active() && client->appState() != APP_STATE_IDLE) {
2304 return desc->mIoHandle;
2305 }
2306 doClose = true;
2307 }
2308 if (doClose) {
2309 closeInput(desc->mIoHandle);
2310 } else {
2311 i++;
2312 }
2313 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002314 }
2315
Eric Laurentfe231122017-11-17 17:48:06 -08002316 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002317
Eric Laurentfe231122017-11-17 17:48:06 -08002318 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2319 lConfig.sample_rate = profileSamplingRate;
2320 lConfig.channel_mask = profileChannelMask;
2321 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002322
François Gaffie11d30102018-11-02 16:09:09 +01002323 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002324
2325 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002326 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002327 (profileSamplingRate != lConfig.sample_rate) ||
2328 !audio_formats_match(profileFormat, lConfig.format) ||
2329 (profileChannelMask != lConfig.channel_mask)) {
2330 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002331 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002332 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002333 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002334 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002335 }
Eric Laurent599c7582015-12-07 18:05:55 -08002336 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002337 }
2338
Eric Laurentc722f302014-12-10 11:21:49 -08002339 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002340
Eric Laurent599c7582015-12-07 18:05:55 -08002341 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002342 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002343
Eric Laurent599c7582015-12-07 18:05:55 -08002344 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002345}
2346
Eric Laurent4eb58f12018-12-07 16:41:02 -08002347status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002348{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002349 ALOGV("%s portId %d", __FUNCTION__, portId);
2350
2351 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2352 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002353 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent717bc282020-08-21 17:10:39 -07002354 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002355 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002356 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002357 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002358 if (client->active()) {
2359 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2360 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002361 }
2362
Eric Laurent8f42ea12018-08-08 09:08:25 -07002363 audio_session_t session = client->session();
2364
Eric Laurent4eb58f12018-12-07 16:41:02 -08002365 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002366
Eric Laurent4eb58f12018-12-07 16:41:02 -08002367 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002368
Eric Laurent4eb58f12018-12-07 16:41:02 -08002369 status_t status = inputDesc->start();
2370 if (status != NO_ERROR) {
2371 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002372 }
Eric Laurente552edb2014-03-10 17:42:56 -07002373
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002374 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002375 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002376 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002377
Eric Laurent8f42ea12018-08-08 09:08:25 -07002378 // indicate active capture to sound trigger service if starting capture from a mic on
2379 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002380 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002381 if (device != nullptr) {
2382 status = setInputDevice(input, device, true /* force */);
2383 } else {
2384 ALOGW("%s no new input device can be found for descriptor %d",
2385 __FUNCTION__, inputDesc->getId());
2386 status = BAD_VALUE;
2387 }
Eric Laurente552edb2014-03-10 17:42:56 -07002388
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002389 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002390 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002391 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002392 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002393 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2394 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002395 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002396 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002397
François Gaffie11d30102018-11-02 16:09:09 +01002398 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2399 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002400 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002401 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002402 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002403
Eric Laurent8f42ea12018-08-08 09:08:25 -07002404 // automatically enable the remote submix output when input is started if not
2405 // used by a policy mix of type MIX_TYPE_RECORDERS
2406 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002407 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002408 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002409 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002410 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002411 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2412 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002413 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002414 if (address != "") {
2415 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2416 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002417 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002418 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002419 }
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002420 } else if (status != NO_ERROR) {
2421 // Restore client activity state.
2422 inputDesc->setClientActive(client, false);
2423 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002424 }
2425
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002426 ALOGV("%s input %d source = %d status = %d exit",
2427 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002428
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002429 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002430}
2431
Eric Laurent8fc147b2018-07-22 19:13:55 -07002432status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002433{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002434 ALOGV("%s portId %d", __FUNCTION__, portId);
2435
2436 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2437 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002438 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002439 return BAD_VALUE;
2440 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002441 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002442 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002443 if (!client->active()) {
2444 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002445 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002446 }
2447
Eric Laurent8f42ea12018-08-08 09:08:25 -07002448 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002449
Eric Laurent8f42ea12018-08-08 09:08:25 -07002450 inputDesc->stop();
2451 if (inputDesc->isActive()) {
2452 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2453 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002454 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002455 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002456 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002457 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2458 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002459 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002460 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002461
2462 // automatically disable the remote submix output when input is stopped if not
2463 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002464 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002465 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002466 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002467 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002468 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2469 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002470 }
2471 if (address != "") {
2472 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2473 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002474 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002475 }
2476 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002477 resetInputDevice(input);
2478
2479 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2480 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002481 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2482 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002483 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002484 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002485 }
2486 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002487 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002488 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002489}
2490
Eric Laurent8fc147b2018-07-22 19:13:55 -07002491void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002492{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002493 ALOGV("%s portId %d", __FUNCTION__, portId);
2494
2495 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2496 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002497 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002498 return;
2499 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002500 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002501 audio_io_handle_t input = inputDesc->mIoHandle;
2502
Eric Laurent8f42ea12018-08-08 09:08:25 -07002503 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002504
Andy Hung39efb7a2018-09-26 15:39:28 -07002505 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002506
Andy Hung39efb7a2018-09-26 15:39:28 -07002507 if (inputDesc->getClientCount() > 0) {
2508 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002509 return;
2510 }
2511
Eric Laurent05b90f82014-08-27 15:32:29 -07002512 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002513 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002514 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002515}
2516
Eric Laurent8f42ea12018-08-08 09:08:25 -07002517void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002518{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002519 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002520
2521 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002522 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002523 }
2524}
2525
Eric Laurent8f42ea12018-08-08 09:08:25 -07002526void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2527{
2528 stopInput(portId);
2529 releaseInput(portId);
2530}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002531
Eric Laurent0dd51852019-04-19 18:18:58 -07002532void AudioPolicyManager::checkCloseInputs() {
2533 // After connecting or disconnecting an input device, close input if:
2534 // - it has no client (was just opened to check profile) OR
2535 // - none of its supported devices are connected anymore OR
2536 // - one of its clients cannot be routed to one of its supported
2537 // devices anymore. Otherwise update device selection
2538 std::vector<audio_io_handle_t> inputsToClose;
2539 for (size_t i = 0; i < mInputs.size(); i++) {
2540 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2541 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002542 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002543 inputsToClose.push_back(mInputs.keyAt(i));
2544 } else {
2545 bool close = false;
2546 for (const auto& client : input->clientsList()) {
2547 sp<DeviceDescriptor> device =
2548 mEngine->getInputDeviceForAttributes(client->attributes());
2549 if (!input->supportedDevices().contains(device)) {
2550 close = true;
2551 break;
2552 }
2553 }
2554 if (close) {
2555 inputsToClose.push_back(mInputs.keyAt(i));
2556 } else {
2557 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2558 }
2559 }
2560 }
2561
2562 for (const audio_io_handle_t handle : inputsToClose) {
2563 ALOGV("%s closing input %d", __func__, handle);
2564 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002565 }
Eric Laurentd4692962014-05-05 18:13:44 -07002566}
2567
François Gaffie251c7f02018-11-07 10:41:08 +01002568void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002569{
2570 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002571 if (indexMin < 0 || indexMax < 0) {
2572 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2573 return;
2574 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002575 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002576
2577 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002578 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2579 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002580 continue;
2581 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002582 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002583 }
Eric Laurente552edb2014-03-10 17:42:56 -07002584}
2585
Eric Laurente0720872014-03-11 09:30:41 -07002586status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002587 int index,
2588 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002589{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002590 auto attributes = mEngine->getAttributesForStreamType(stream);
Francois Gaffie5992b182020-03-20 14:55:14 +01002591 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2592 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2593 return NO_ERROR;
2594 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002595 ALOGV("%s: stream %s attributes=%s", __func__,
2596 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002597 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002598}
2599
Eric Laurente0720872014-03-11 09:30:41 -07002600status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002601 int *index,
2602 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002603{
François Gaffiec005e562018-11-06 15:04:49 +01002604 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2605 // stream by the engine.
jiabin12dc6b02019-10-01 09:38:30 -07002606 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002607 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin12dc6b02019-10-01 09:38:30 -07002608 deviceTypes = mEngine->getOutputDevicesForStream(
2609 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002610 }
jiabin12dc6b02019-10-01 09:38:30 -07002611 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002612}
2613
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002614status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002615 int index,
2616 audio_devices_t device)
2617{
2618 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002619 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2620 if (group == VOLUME_GROUP_NONE) {
2621 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002622 return BAD_VALUE;
2623 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002624 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002625 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002626 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002627 VolumeSource vs = toVolumeSource(group);
2628 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2629
2630 status = setVolumeCurveIndex(index, device, curves);
2631 if (status != NO_ERROR) {
2632 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2633 return status;
2634 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002635
jiabin12dc6b02019-10-01 09:38:30 -07002636 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002637 auto curCurvAttrs = curves.getAttributes();
2638 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2639 auto attr = curCurvAttrs.front();
jiabin12dc6b02019-10-01 09:38:30 -07002640 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002641 } else if (!curves.getStreamTypes().empty()) {
2642 auto stream = curves.getStreamTypes().front();
jiabin12dc6b02019-10-01 09:38:30 -07002643 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002644 } else {
2645 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2646 return BAD_VALUE;
2647 }
jiabin12dc6b02019-10-01 09:38:30 -07002648 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2649 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002650
François Gaffiecfe17322018-11-07 13:41:29 +01002651 // update volume on all outputs and streams matching the following:
2652 // - The requested stream (or a stream matching for volume control) is active on the output
2653 // - The device (or devices) selected by the engine for this stream includes
2654 // the requested device
2655 // - For non default requested device, currently selected device on the output is either the
2656 // requested device or one of the devices selected by the engine for this stream
2657 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2658 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002659 for (size_t i = 0; i < mOutputs.size(); i++) {
2660 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin12dc6b02019-10-01 09:38:30 -07002661 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002662
jiabin12dc6b02019-10-01 09:38:30 -07002663 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2664 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002665 }
François Gaffieed91f582020-01-31 10:35:37 +01002666 if (!(desc->isActive(vs) || isInCall())) {
2667 continue;
2668 }
2669 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2670 curDevices.find(device) == curDevices.end()) {
2671 continue;
2672 }
2673 bool applyVolume = false;
2674 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2675 curSrcDevices.insert(device);
2676 applyVolume = (curSrcDevices.find(
2677 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2678 } else {
2679 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2680 }
2681 if (!applyVolume) {
2682 continue; // next output
2683 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002684 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2685 // If a higher priority strategy is active, and the output is routed to a device with a
2686 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002687 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002688 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002689 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2690 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2691 false /*preferredDevice*/);
2692 if (activeClients.empty()) {
2693 continue;
2694 }
2695 bool isPreempted = false;
2696 bool isHigherPriority = productStrategy < strategy;
2697 for (const auto &client : activeClients) {
2698 if (isHigherPriority && (client->volumeSource() != vs)) {
2699 ALOGV("%s: Strategy=%d (\nrequester:\n"
2700 " group %d, volumeGroup=%d attributes=%s)\n"
2701 " higher priority source active:\n"
2702 " volumeGroup=%d attributes=%s) \n"
2703 " on output %zu, bailing out", __func__, productStrategy,
2704 group, group, toString(attributes).c_str(),
2705 client->volumeSource(), toString(client->attributes()).c_str(), i);
2706 applyVolume = false;
2707 isPreempted = true;
2708 break;
2709 }
2710 // However, continue for loop to ensure no higher prio clients running on output
2711 if (client->volumeSource() == vs) {
2712 applyVolume = true;
2713 }
2714 }
2715 if (isPreempted || applyVolume) {
2716 break;
2717 }
2718 }
2719 if (!applyVolume) {
2720 continue; // next output
2721 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002722 }
François Gaffieed91f582020-01-31 10:35:37 +01002723 //FIXME: workaround for truncated touch sounds
2724 // delayed volume change for system stream to be removed when the problem is
2725 // handled by system UI
2726 status_t volStatus = checkAndSetVolume(
2727 curves, vs, index, desc, curDevices,
2728 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2729 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2730 if (volStatus != NO_ERROR) {
2731 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002732 }
2733 }
François Gaffiecfe17322018-11-07 13:41:29 +01002734 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2735 return status;
2736}
2737
François Gaffieaaac0fd2018-11-22 17:56:39 +01002738status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002739 audio_devices_t device,
2740 IVolumeCurves &volumeCurves)
2741{
2742 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2743 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002744 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2745 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002746 (index > volumeCurves.getVolumeIndexMax())) {
2747 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2748 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2749 return BAD_VALUE;
2750 }
2751 if (!audio_is_output_device(device)) {
2752 return BAD_VALUE;
2753 }
2754
2755 // Force max volume if stream cannot be muted
2756 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2757
François Gaffieaaac0fd2018-11-22 17:56:39 +01002758 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002759 volumeCurves.addCurrentVolumeIndex(device, index);
2760 return NO_ERROR;
2761}
2762
2763status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2764 int &index,
2765 audio_devices_t device)
2766{
2767 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2768 // stream by the engine.
jiabin12dc6b02019-10-01 09:38:30 -07002769 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002770 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin12dc6b02019-10-01 09:38:30 -07002771 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2772 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002773 }
jiabin12dc6b02019-10-01 09:38:30 -07002774 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002775}
2776
2777status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2778 int &index,
jiabin12dc6b02019-10-01 09:38:30 -07002779 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002780{
jiabin12dc6b02019-10-01 09:38:30 -07002781 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002782 return BAD_VALUE;
2783 }
jiabin12dc6b02019-10-01 09:38:30 -07002784 index = curves.getVolumeIndex(deviceTypes);
2785 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002786 return NO_ERROR;
2787}
2788
2789status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2790 int &index)
2791{
2792 index = getVolumeCurves(attr).getVolumeIndexMin();
2793 return NO_ERROR;
2794}
2795
2796status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2797 int &index)
2798{
2799 index = getVolumeCurves(attr).getVolumeIndexMax();
2800 return NO_ERROR;
2801}
2802
Eric Laurent36829f92017-04-07 19:04:42 -07002803audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002804{
2805 // select one output among several suitable for global effects.
2806 // The priority is as follows:
2807 // 1: An offloaded output. If the effect ends up not being offloadable,
2808 // AudioFlinger will invalidate the track and the offloaded output
2809 // will be closed causing the effect to be moved to a PCM output.
2810 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002811 // 3: The primary output
2812 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002813
François Gaffiec005e562018-11-06 15:04:49 +01002814 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2815 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002816 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002817
Eric Laurent36829f92017-04-07 19:04:42 -07002818 if (outputs.size() == 0) {
2819 return AUDIO_IO_HANDLE_NONE;
2820 }
Eric Laurente552edb2014-03-10 17:42:56 -07002821
Eric Laurent36829f92017-04-07 19:04:42 -07002822 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2823 bool activeOnly = true;
2824
2825 while (output == AUDIO_IO_HANDLE_NONE) {
2826 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2827 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2828 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2829
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002830 for (audio_io_handle_t output : outputs) {
2831 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002832 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002833 continue;
2834 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002835 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2836 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002837 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002838 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002839 }
2840 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002841 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002842 }
2843 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002844 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002845 }
2846 }
2847 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2848 output = outputOffloaded;
2849 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2850 output = outputDeepBuffer;
2851 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2852 output = outputPrimary;
2853 } else {
2854 output = outputs[0];
2855 }
2856 activeOnly = false;
2857 }
2858
2859 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002860 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002861 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2862 mMusicEffectOutput = output;
2863 }
2864
2865 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002866 return output;
2867}
2868
Eric Laurent36829f92017-04-07 19:04:42 -07002869audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2870{
2871 return selectOutputForMusicEffects();
2872}
2873
Eric Laurente0720872014-03-11 09:30:41 -07002874status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002875 audio_io_handle_t io,
2876 uint32_t strategy,
2877 int session,
2878 int id)
2879{
Eric Laurent9b2064c2019-11-22 17:25:04 -08002880 if (session != AUDIO_SESSION_DEVICE) {
2881 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07002882 if (index < 0) {
Eric Laurent9b2064c2019-11-22 17:25:04 -08002883 index = mInputs.indexOfKey(io);
2884 if (index < 0) {
2885 ALOGW("registerEffect() unknown io %d", io);
2886 return INVALID_OPERATION;
2887 }
Eric Laurente552edb2014-03-10 17:42:56 -07002888 }
2889 }
François Gaffiec005e562018-11-06 15:04:49 +01002890 return mEffects.registerEffect(desc, io, session, id,
2891 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
2892 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07002893}
2894
Eric Laurentc241b0d2018-11-28 09:08:49 -08002895status_t AudioPolicyManager::unregisterEffect(int id)
2896{
2897 if (mEffects.getEffect(id) == nullptr) {
2898 return INVALID_OPERATION;
2899 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08002900 if (mEffects.isEffectEnabled(id)) {
2901 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2902 setEffectEnabled(id, false);
2903 }
2904 return mEffects.unregisterEffect(id);
2905}
2906
2907status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2908{
2909 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2910 if (effect == nullptr) {
2911 return INVALID_OPERATION;
2912 }
2913
2914 status_t status = mEffects.setEffectEnabled(id, enabled);
2915 if (status == NO_ERROR) {
2916 mInputs.trackEffectEnabled(effect, enabled);
2917 }
2918 return status;
2919}
2920
Eric Laurent6c796322019-04-09 14:13:17 -07002921
2922status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
2923{
2924 mEffects.moveEffects(ids, io);
2925 return NO_ERROR;
2926}
2927
Eric Laurentc75307b2015-03-17 15:29:32 -07002928bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2929{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002930 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002931}
2932
2933bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2934{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002935 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002936}
2937
Eric Laurente0720872014-03-11 09:30:41 -07002938bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002939{
2940 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002941 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002942 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002943 return true;
2944 }
2945 }
2946 return false;
2947}
2948
Eric Laurent275e8e92014-11-30 15:14:47 -08002949// Register a list of custom mixes with their attributes and format.
2950// When a mix is registered, corresponding input and output profiles are
2951// added to the remote submix hw module. The profile contains only the
2952// parameters (sampling rate, format...) specified by the mix.
2953// The corresponding input remote submix device is also connected.
2954//
2955// When a remote submix device is connected, the address is checked to select the
2956// appropriate profile and the corresponding input or output stream is opened.
2957//
2958// When capture starts, getInputForAttr() will:
2959// - 1 look for a mix matching the address passed in attribtutes tags if any
2960// - 2 if none found, getDeviceForInputSource() will:
2961// - 2.1 look for a mix matching the attributes source
2962// - 2.2 if none found, default to device selection by policy rules
2963// At this time, the corresponding output remote submix device is also connected
2964// and active playback use cases can be transferred to this mix if needed when reconnecting
2965// after AudioTracks are invalidated
2966//
2967// When playback starts, getOutputForAttr() will:
2968// - 1 look for a mix matching the address passed in attribtutes tags if any
2969// - 2 if none found, look for a mix matching the attributes usage
2970// - 3 if none found, default to device and output selection by policy rules.
2971
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002972status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002973{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002974 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2975 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07002976 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002977 sp<HwModule> rSubmixModule;
2978 // examine each mix's route type
2979 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002980 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08002981 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
2982 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
2983 ALOGE("Unsupported Policy Mix %zu of %zu: "
2984 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
2985 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002986 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002987 break;
2988 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002989 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
2990 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07002991 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002992 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
2993 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002994 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002995 rSubmixModule = mHwModules.getModuleFromName(
2996 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2997 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002998 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08002999 i);
3000 res = INVALID_OPERATION;
3001 break;
3002 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003003 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003004
Eric Laurent97ac8712018-07-27 18:59:02 -07003005 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003006 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003007 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003008 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003009 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3010 } else {
3011 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3012 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003013 }
François Gaffie036e1e92015-03-19 10:16:24 +01003014
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003015 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003016 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003017 res = INVALID_OPERATION;
3018 break;
3019 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003020 audio_config_t outputConfig = mix.mFormat;
3021 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003022 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3023 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003024 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3025 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabineaf09f02019-08-19 15:08:30 -07003026 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003027 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabineaf09f02019-08-19 15:08:30 -07003028 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003029 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003030
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003031 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003032 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3033 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3034 ALOGE("Failed to set remote submix device available, type %u, address %s",
3035 mix.mDeviceType, address.string());
3036 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003037 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003038 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3039 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003040 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003041 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003042 i, mixes.size(), type, address.string());
3043
3044 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3045 mix.mDeviceType, mix.mDeviceAddress,
3046 String8(), AUDIO_FORMAT_DEFAULT);
3047 if (device == nullptr) {
3048 res = INVALID_OPERATION;
3049 break;
3050 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003051
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003052 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003053 // First try to find an already opened output supporting the device
3054 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003055 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003056
Eric Laurentc529cf62020-04-17 18:19:10 -07003057 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003058 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003059 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3060 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003061 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003062 } else {
3063 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003064 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003065 }
3066 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003067 // If no output found, try to find a direct output profile supporting the device
3068 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3069 sp<HwModule> module = mHwModules[i];
3070 for (size_t j = 0;
3071 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3072 j++) {
3073 sp<IOProfile> profile = module->getOutputProfiles()[j];
3074 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3075 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3076 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3077 address.string());
3078 res = INVALID_OPERATION;
3079 } else {
3080 foundOutput = true;
3081 }
3082 }
3083 }
3084 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003085 if (res != NO_ERROR) {
3086 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003087 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003088 res = INVALID_OPERATION;
3089 break;
3090 } else if (!foundOutput) {
3091 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003092 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003093 res = INVALID_OPERATION;
3094 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003095 } else {
3096 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003097 }
Eric Laurentc722f302014-12-10 11:21:49 -08003098 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003099 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003100 if (res != NO_ERROR) {
3101 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003102 } else if (checkOutputs) {
3103 checkForDeviceAndOutputChanges();
3104 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003105 }
3106 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003107}
3108
3109status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3110{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003111 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003112 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003113 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003114 sp<HwModule> rSubmixModule;
3115 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003116 for (const auto& mix : mixes) {
3117 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003118
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003119 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003120 rSubmixModule = mHwModules.getModuleFromName(
3121 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3122 if (rSubmixModule == 0) {
3123 res = INVALID_OPERATION;
3124 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003125 }
3126 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003127
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003128 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003129
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003130 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003131 res = INVALID_OPERATION;
3132 continue;
3133 }
3134
Kevin Rocard04ed0462019-05-02 17:53:24 -07003135 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3136 if (getDeviceConnectionState(device, address.string()) ==
3137 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3138 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3139 address.string(), "remote-submix",
3140 AUDIO_FORMAT_DEFAULT);
3141 if (res != OK) {
3142 ALOGE("Error making RemoteSubmix device unavailable for mix "
3143 "with type %d, address %s", device, address.string());
3144 }
3145 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003146 }
jiabineaf09f02019-08-19 15:08:30 -07003147 rSubmixModule->removeOutputProfile(address.c_str());
3148 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003149
Kevin Rocard153f92d2018-12-18 18:33:28 -08003150 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003151 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003152 res = INVALID_OPERATION;
3153 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003154 } else {
3155 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003156 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003157 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003158 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003159 if (res == NO_ERROR && checkOutputs) {
3160 checkForDeviceAndOutputChanges();
3161 updateCallAndOutputRouting();
3162 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003163 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003164}
3165
Mikhail Naganov100f0122018-11-29 11:22:16 -08003166void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3167{
3168 size_t i = 0;
3169 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3170 for (const auto& fmt : mManualSurroundFormats) {
3171 if (i++ != 0) dst->append(", ");
3172 std::string sfmt;
3173 FormatConverter::toString(fmt, sfmt);
3174 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3175 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3176 }
3177}
3178
Eric Laurentc529cf62020-04-17 18:19:10 -07003179// Returns true if all devices types match the predicate and are supported by one HW module
3180bool AudioPolicyManager::areAllDevicesSupported(
jiabinc1afe3b2020-08-07 11:56:38 -07003181 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003182 std::function<bool(audio_devices_t)> predicate,
3183 const char *context) {
3184 for (size_t i = 0; i < devices.size(); i++) {
3185 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin4e826212020-08-07 17:32:40 -07003186 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003187 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003188 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang6e468242020-09-03 17:54:16 +00003189 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin4e826212020-08-07 17:32:40 -07003190 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003191 return false;
3192 }
3193 }
3194 return true;
3195}
3196
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003197status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabinc1afe3b2020-08-07 11:56:38 -07003198 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003199 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003200 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3201 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003202 }
3203 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003204 if (res != NO_ERROR) {
3205 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3206 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003207 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003208
3209 checkForDeviceAndOutputChanges();
3210 updateCallAndOutputRouting();
3211
3212 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003213}
3214
3215status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3216 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003217 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3218 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003219 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003220 __FUNCTION__, uid);
3221 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003222 }
3223
Eric Laurentc529cf62020-04-17 18:19:10 -07003224 checkForDeviceAndOutputChanges();
3225 updateCallAndOutputRouting();
3226
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003227 return res;
3228}
3229
Eric Laurentcca11ce2020-11-25 15:31:27 +01003230
jiabin4e826212020-08-07 17:32:40 -07003231status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3232 device_role_t role,
3233 const AudioDeviceTypeAddrVector &devices) {
3234 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3235 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003236
Eric Laurentc529cf62020-04-17 18:19:10 -07003237 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003238 return BAD_VALUE;
3239 }
jiabin4e826212020-08-07 17:32:40 -07003240 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003241 if (status != NO_ERROR) {
jiabin4e826212020-08-07 17:32:40 -07003242 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3243 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003244 return status;
3245 }
3246
3247 checkForDeviceAndOutputChanges();
Eric Laurentcca11ce2020-11-25 15:31:27 +01003248
3249 bool forceVolumeReeval = false;
3250 // FIXME: workaround for truncated touch sounds
3251 // to be removed when the problem is handled by system UI
3252 uint32_t delayMs = 0;
3253 if (strategy == mCommunnicationStrategy) {
3254 forceVolumeReeval = true;
3255 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3256 updateInputRouting();
3257 }
3258 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003259
3260 return NO_ERROR;
3261}
3262
3263void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3264{
3265 uint32_t waitMs = 0;
Francois Gaffie9da281d2021-02-04 17:02:59 +01003266 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurente1f1cb52020-08-21 12:50:41 -07003267 // Only apply special touch sound delay once
3268 delayMs = 0;
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003269 }
3270 for (size_t i = 0; i < mOutputs.size(); i++) {
3271 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3272 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3273 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3274 // As done in setDeviceConnectionState, we could also fix default device issue by
3275 // preventing the force re-routing in case of default dev that distinguishes on address.
3276 // Let's give back to engine full device choice decision however.
3277 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurente1f1cb52020-08-21 12:50:41 -07003278 // Only apply special touch sound delay once
3279 delayMs = 0;
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003280 }
3281 if (forceVolumeReeval && !newDevices.isEmpty()) {
3282 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3283 }
3284 }
3285}
3286
Eric Laurentcca11ce2020-11-25 15:31:27 +01003287void AudioPolicyManager::updateInputRouting() {
3288 for (const auto& activeDesc : mInputs.getActiveInputs()) {
3289 auto newDevice = getNewInputDevice(activeDesc);
3290 // Force new input selection if the new device can not be reached via current input
3291 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3292 setInputDevice(activeDesc->mIoHandle, newDevice);
3293 } else {
3294 closeInput(activeDesc->mIoHandle);
3295 }
3296 }
3297}
3298
jiabin4e826212020-08-07 17:32:40 -07003299status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3300 device_role_t role)
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003301{
jiabin4e826212020-08-07 17:32:40 -07003302 ALOGI("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003303
jiabin4e826212020-08-07 17:32:40 -07003304 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003305 if (status != NO_ERROR) {
Eric Laurentcca11ce2020-11-25 15:31:27 +01003306 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3307 strategy, status);
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003308 return status;
3309 }
3310
3311 checkForDeviceAndOutputChanges();
Eric Laurentcca11ce2020-11-25 15:31:27 +01003312
3313 bool forceVolumeReeval = false;
3314 // FIXME: workaround for truncated touch sounds
3315 // to be removed when the problem is handled by system UI
3316 uint32_t delayMs = 0;
3317 if (strategy == mCommunnicationStrategy) {
3318 forceVolumeReeval = true;
3319 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3320 updateInputRouting();
3321 }
3322 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003323
3324 return NO_ERROR;
3325}
3326
jiabin4e826212020-08-07 17:32:40 -07003327status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3328 device_role_t role,
3329 AudioDeviceTypeAddrVector &devices) {
3330 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003331}
3332
Jiabin Huang6e468242020-09-03 17:54:16 +00003333status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3334 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3335 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3336 dumpAudioDeviceTypeAddrVector(devices).c_str());
3337
3338 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
3339 return BAD_VALUE;
3340 }
3341 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3342 ALOGW_IF(status != NO_ERROR,
3343 "Engine could not set preferred devices %s for audio source %d role %d",
3344 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3345
3346 return status;
3347}
3348
3349status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3350 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3351 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3352 dumpAudioDeviceTypeAddrVector(devices).c_str());
3353
3354 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
3355 return BAD_VALUE;
3356 }
3357 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3358 ALOGW_IF(status != NO_ERROR,
3359 "Engine could not add preferred devices %s for audio source %d role %d",
3360 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3361
Eric Laurentcca11ce2020-11-25 15:31:27 +01003362 updateInputRouting();
Jiabin Huang6e468242020-09-03 17:54:16 +00003363 return status;
3364}
3365
3366status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3367 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3368{
3369 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3370 dumpAudioDeviceTypeAddrVector(devices).c_str());
3371
3372 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
3373 return BAD_VALUE;
3374 }
3375
3376 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3377 audioSource, role, devices);
3378 ALOGW_IF(status != NO_ERROR,
3379 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3380
Eric Laurentcca11ce2020-11-25 15:31:27 +01003381 updateInputRouting();
Jiabin Huang6e468242020-09-03 17:54:16 +00003382 return status;
3383}
3384
3385status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3386 device_role_t role) {
3387 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3388
3389 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3390 ALOGW_IF(status != NO_ERROR,
3391 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3392
Eric Laurentcca11ce2020-11-25 15:31:27 +01003393 updateInputRouting();
Jiabin Huang6e468242020-09-03 17:54:16 +00003394 return status;
3395}
3396
3397status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3398 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3399 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3400}
3401
Oscar Azucena90e77632019-11-27 17:12:28 -08003402status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabinc1afe3b2020-08-07 11:56:38 -07003403 const AudioDeviceTypeAddrVector& devices) {
3404 ALOGI("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003405 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3406 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003407 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003408 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3409 if (status != NO_ERROR) {
3410 ALOGE("%s() could not set device affinity for userId %d",
3411 __FUNCTION__, userId);
3412 return status;
3413 }
3414
3415 // reevaluate outputs for all devices
3416 checkForDeviceAndOutputChanges();
3417 updateCallAndOutputRouting();
3418
3419 return NO_ERROR;
3420}
3421
3422status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
3423 ALOGI("%s() userId=%d", __FUNCTION__, userId);
3424 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3425 if (status != NO_ERROR) {
3426 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3427 __FUNCTION__, userId);
3428 return status;
3429 }
3430
3431 // reevaluate outputs for all devices
3432 checkForDeviceAndOutputChanges();
3433 updateCallAndOutputRouting();
3434
3435 return NO_ERROR;
3436}
3437
Andy Hungc29d82b2018-10-05 12:23:17 -07003438void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003439{
Andy Hungc29d82b2018-10-05 12:23:17 -07003440 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3441 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003442 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003443 std::string stateLiteral;
3444 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003445 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003446 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3447 "communications", "media", "record", "dock", "system",
3448 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3449 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3450 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003451 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3452 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3453 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3454 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3455 dst->append(" (MANUAL: ");
3456 dumpManualSurroundFormats(dst);
3457 dst->append(")");
3458 }
3459 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003460 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003461 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3462 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurentcca11ce2020-11-25 15:31:27 +01003463 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003464 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurentcca11ce2020-11-25 15:31:27 +01003465
Andy Hungc29d82b2018-10-05 12:23:17 -07003466 mAvailableOutputDevices.dump(dst, String8("Available output"));
3467 mAvailableInputDevices.dump(dst, String8("Available input"));
3468 mHwModulesAll.dump(dst);
3469 mOutputs.dump(dst);
3470 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003471 mEffects.dump(dst);
3472 mAudioPatches.dump(dst);
3473 mPolicyMixes.dump(dst);
3474 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003475
Kevin Rocardb99cc752019-03-21 20:52:24 -07003476 dst->appendFormat(" AllowedCapturePolicies:\n");
3477 for (auto& policy : mAllowedCapturePolicies) {
3478 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3479 }
3480
François Gaffiec005e562018-11-06 15:04:49 +01003481 dst->appendFormat("\nPolicy Engine dump:\n");
3482 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003483}
3484
3485status_t AudioPolicyManager::dump(int fd)
3486{
3487 String8 result;
3488 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003489 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003490 return NO_ERROR;
3491}
3492
Kevin Rocardb99cc752019-03-21 20:52:24 -07003493status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3494{
3495 mAllowedCapturePolicies[uid] = capturePolicy;
3496 return NO_ERROR;
3497}
3498
Eric Laurente552edb2014-03-10 17:42:56 -07003499// This function checks for the parameters which can be offloaded.
3500// This can be enhanced depending on the capability of the DSP and policy
3501// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07003502bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003503{
3504 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003505 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07003506 offloadInfo.sample_rate, offloadInfo.channel_mask,
3507 offloadInfo.format,
3508 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3509 offloadInfo.has_video);
3510
Andy Hung2ddee192015-12-18 17:34:44 -08003511 if (mMasterMono) {
3512 return false; // no offloading if mono is set.
3513 }
3514
Eric Laurente552edb2014-03-10 17:42:56 -07003515 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003516 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3517 ALOGV("offload disabled by audio.offload.disable");
3518 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07003519 }
3520
3521 // Check if stream type is music, then only allow offload as of now.
3522 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3523 {
3524 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
3525 return false;
3526 }
3527
3528 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003529 const bool allowOffloadWithVideo =
3530 property_get_bool("audio.offload.video", false /* default_value */);
3531 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07003532 ALOGV("isOffloadSupported: has_video == true, returning false");
3533 return false;
3534 }
3535
3536 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003537 const int min_duration_secs = property_get_int32(
3538 "audio.offload.min.duration.secs", -1 /* default_value */);
3539 if (min_duration_secs >= 0) {
3540 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
3541 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3542 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07003543 return false;
3544 }
3545 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
3546 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3547 return false;
3548 }
3549
3550 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3551 // creating an offloaded track and tearing it down immediately after start when audioflinger
3552 // detects there is an active non offloadable effect.
3553 // FIXME: We should check the audio session here but we do not have it in this context.
3554 // This may prevent offloading in rare situations where effects are left active by apps
3555 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003556 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003557 return false;
3558 }
3559
3560 // See if there is a profile to support this.
3561 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003562 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003563 offloadInfo.sample_rate,
3564 offloadInfo.format,
3565 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003566 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3567 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07003568 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
3569 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07003570}
3571
Michael Chana94fbb22018-04-24 14:31:19 +10003572bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3573 const audio_attributes_t& attributes) {
3574 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003575 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003576 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003577 config.sample_rate,
3578 config.format,
3579 config.channel_mask,
3580 output_flags,
3581 true /* directOnly */);
3582 ALOGV("%s() profile %sfound with name: %s, "
3583 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3584 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabineaf09f02019-08-19 15:08:30 -07003585 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003586 config.sample_rate, config.format, config.channel_mask, output_flags);
3587 return (profile != 0);
3588}
3589
Eric Laurent6a94d692014-05-20 11:18:06 -07003590status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3591 audio_port_type_t type,
3592 unsigned int *num_ports,
3593 struct audio_port *ports,
3594 unsigned int *generation)
3595{
3596 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
3597 generation == NULL) {
3598 return BAD_VALUE;
3599 }
3600 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
3601 if (ports == NULL) {
3602 *num_ports = 0;
3603 }
3604
3605 size_t portsWritten = 0;
3606 size_t portsMax = *num_ports;
3607 *num_ports = 0;
3608 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003609 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3610 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003611 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003612 for (const auto& dev : mAvailableOutputDevices) {
3613 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003614 continue;
3615 }
3616 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003617 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003618 }
3619 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003620 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003621 }
3622 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003623 for (const auto& dev : mAvailableInputDevices) {
3624 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003625 continue;
3626 }
3627 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003628 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003629 }
3630 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003631 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003632 }
3633 }
3634 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3635 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3636 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3637 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3638 }
3639 *num_ports += mInputs.size();
3640 }
3641 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003642 size_t numOutputs = 0;
3643 for (size_t i = 0; i < mOutputs.size(); i++) {
3644 if (!mOutputs[i]->isDuplicated()) {
3645 numOutputs++;
3646 if (portsWritten < portsMax) {
3647 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3648 }
3649 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003650 }
Eric Laurent84c70242014-06-23 08:46:27 -07003651 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003652 }
3653 }
3654 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003655 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003656 return NO_ERROR;
3657}
3658
Eric Laurent99fcae42018-05-17 16:59:18 -07003659status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003660{
Eric Laurent99fcae42018-05-17 16:59:18 -07003661 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3662 return BAD_VALUE;
3663 }
3664 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3665 if (dev != 0) {
3666 dev->toAudioPort(port);
3667 return NO_ERROR;
3668 }
3669 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3670 if (dev != 0) {
3671 dev->toAudioPort(port);
3672 return NO_ERROR;
3673 }
3674 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3675 if (out != 0) {
3676 out->toAudioPort(port);
3677 return NO_ERROR;
3678 }
3679 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3680 if (in != 0) {
3681 in->toAudioPort(port);
3682 return NO_ERROR;
3683 }
3684 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003685}
3686
François Gaffiead447b72019-11-18 15:50:22 +01003687status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3688 audio_patch_handle_t *handle,
3689 uid_t uid, uint32_t delayMs,
3690 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003691{
François Gaffiead447b72019-11-18 15:50:22 +01003692 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003693 if (handle == NULL || patch == NULL) {
3694 return BAD_VALUE;
3695 }
François Gaffiead447b72019-11-18 15:50:22 +01003696 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003697
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003698 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003699 return BAD_VALUE;
3700 }
3701 // only one source per audio patch supported for now
3702 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003703 return INVALID_OPERATION;
3704 }
Eric Laurent874c42872014-08-08 15:13:39 -07003705
3706 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003707 return INVALID_OPERATION;
3708 }
Eric Laurent874c42872014-08-08 15:13:39 -07003709 for (size_t i = 0; i < patch->num_sinks; i++) {
3710 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3711 return INVALID_OPERATION;
3712 }
3713 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003714
3715 sp<AudioPatch> patchDesc;
3716 ssize_t index = mAudioPatches.indexOfKey(*handle);
3717
François Gaffiead447b72019-11-18 15:50:22 +01003718 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3719 patch->sources[0].role,
3720 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003721#if LOG_NDEBUG == 0
3722 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffiead447b72019-11-18 15:50:22 +01003723 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3724 patch->sinks[i].role,
3725 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003726 }
3727#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003728
3729 if (index >= 0) {
3730 patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01003731 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3732 __func__, mUidCached, patchDesc->getUid(), uid);
3733 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003734 return INVALID_OPERATION;
3735 }
3736 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003737 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003738 }
3739
3740 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003741 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003742 if (outputDesc == NULL) {
François Gaffiead447b72019-11-18 15:50:22 +01003743 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003744 return BAD_VALUE;
3745 }
Eric Laurent84c70242014-06-23 08:46:27 -07003746 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3747 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003748 if (patchDesc != 0) {
3749 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffiead447b72019-11-18 15:50:22 +01003750 ALOGV("%s source id differs for patch current id %d new id %d",
3751 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003752 return BAD_VALUE;
3753 }
3754 }
Eric Laurent874c42872014-08-08 15:13:39 -07003755 DeviceVector devices;
3756 for (size_t i = 0; i < patch->num_sinks; i++) {
3757 // Only support mix to devices connection
3758 // TODO add support for mix to mix connection
3759 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffiead447b72019-11-18 15:50:22 +01003760 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003761 return INVALID_OPERATION;
3762 }
3763 sp<DeviceDescriptor> devDesc =
3764 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3765 if (devDesc == 0) {
François Gaffiead447b72019-11-18 15:50:22 +01003766 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003767 return BAD_VALUE;
3768 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003769
François Gaffie11d30102018-11-02 16:09:09 +01003770 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003771 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003772 NULL, // updatedSamplingRate
3773 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003774 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003775 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003776 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003777 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffiead447b72019-11-18 15:50:22 +01003778 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003779 return INVALID_OPERATION;
3780 }
3781 devices.add(devDesc);
3782 }
3783 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003784 return INVALID_OPERATION;
3785 }
Eric Laurent874c42872014-08-08 15:13:39 -07003786
Eric Laurent6a94d692014-05-20 11:18:06 -07003787 // TODO: reconfigure output format and channels here
François Gaffiead447b72019-11-18 15:50:22 +01003788 ALOGV("%s setting device %s on output %d",
3789 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003790 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003791 index = mAudioPatches.indexOfKey(*handle);
3792 if (index >= 0) {
3793 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffiead447b72019-11-18 15:50:22 +01003794 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003795 }
3796 patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01003797 patchDesc->setUid(uid);
3798 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003799 } else {
François Gaffiead447b72019-11-18 15:50:22 +01003800 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003801 return INVALID_OPERATION;
3802 }
3803 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3804 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3805 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003806 // only one sink supported when connecting an input device to a mix
3807 if (patch->num_sinks > 1) {
3808 return INVALID_OPERATION;
3809 }
François Gaffie53615e22015-03-19 09:24:12 +01003810 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003811 if (inputDesc == NULL) {
3812 return BAD_VALUE;
3813 }
3814 if (patchDesc != 0) {
3815 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3816 return BAD_VALUE;
3817 }
3818 }
François Gaffie11d30102018-11-02 16:09:09 +01003819 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003820 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003821 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003822 return BAD_VALUE;
3823 }
3824
François Gaffie11d30102018-11-02 16:09:09 +01003825 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003826 patch->sinks[0].sample_rate,
3827 NULL, /*updatedSampleRate*/
3828 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003829 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003830 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003831 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003832 // FIXME for the parameter type,
3833 // and the NONE
3834 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003835 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003836 return INVALID_OPERATION;
3837 }
3838 // TODO: reconfigure output format and channels here
François Gaffiead447b72019-11-18 15:50:22 +01003839 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003840 device->toString().c_str(), inputDesc->mIoHandle);
3841 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003842 index = mAudioPatches.indexOfKey(*handle);
3843 if (index >= 0) {
3844 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffiead447b72019-11-18 15:50:22 +01003845 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003846 }
3847 patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01003848 patchDesc->setUid(uid);
3849 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003850 } else {
François Gaffiead447b72019-11-18 15:50:22 +01003851 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003852 return INVALID_OPERATION;
3853 }
3854 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3855 // device to device connection
3856 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003857 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003858 return BAD_VALUE;
3859 }
3860 }
François Gaffie11d30102018-11-02 16:09:09 +01003861 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003862 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003863 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003864 return BAD_VALUE;
3865 }
Eric Laurent874c42872014-08-08 15:13:39 -07003866
Eric Laurent6a94d692014-05-20 11:18:06 -07003867 //update source and sink with our own data as the data passed in the patch may
3868 // be incomplete.
François Gaffiead447b72019-11-18 15:50:22 +01003869 PatchBuilder patchBuilder;
3870 audio_port_config sourcePortConfig = {};
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11003871
3872 // if first sink is to MSD, establish single MSD patch
3873 if (getMsdAudioOutDevices().contains(
3874 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
3875 ALOGV("%s patching to MSD", __FUNCTION__);
3876 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
3877 goto installPatch;
3878 }
3879
François Gaffiead447b72019-11-18 15:50:22 +01003880 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
3881 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07003882
Eric Laurent874c42872014-08-08 15:13:39 -07003883 for (size_t i = 0; i < patch->num_sinks; i++) {
3884 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffiead447b72019-11-18 15:50:22 +01003885 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003886 return INVALID_OPERATION;
3887 }
François Gaffie11d30102018-11-02 16:09:09 +01003888 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003889 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003890 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003891 return BAD_VALUE;
3892 }
François Gaffiead447b72019-11-18 15:50:22 +01003893 audio_port_config sinkPortConfig = {};
3894 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
3895 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003896
Francois Gaffie06e324a2020-10-14 18:02:07 +02003897 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
3898 // volume management purpose (tracking activity)
3899 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
3900 // in config XML to reach the sink so that is can be declared as available.
3901 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3902 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
3903 if (sourceDesc != nullptr) {
3904 // take care of dynamic routing for SwOutput selection,
3905 audio_attributes_t attributes = sourceDesc->attributes();
3906 audio_stream_type_t stream = sourceDesc->stream();
3907 audio_attributes_t resultAttr;
3908 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3909 config.sample_rate = sourceDesc->config().sample_rate;
3910 config.channel_mask = sourceDesc->config().channel_mask;
3911 config.format = sourceDesc->config().format;
3912 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3913 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3914 bool isRequestedDeviceForExclusiveUse = false;
3915 output_type_t outputType;
3916 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
3917 &stream, sourceDesc->uid(), &config, &flags,
3918 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
3919 nullptr, &outputType);
3920 if (output == AUDIO_IO_HANDLE_NONE) {
3921 ALOGV("%s no output for device %s",
3922 __FUNCTION__, sinkDevice->toString().c_str());
3923 return INVALID_OPERATION;
3924 }
3925 outputDesc = mOutputs.valueFor(output);
3926 if (outputDesc->isDuplicated()) {
3927 ALOGE("%s output is duplicated", __func__);
3928 return INVALID_OPERATION;
3929 }
3930 sourceDesc->setSwOutput(outputDesc);
3931 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07003932 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003933 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003934 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003935 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffiead447b72019-11-18 15:50:22 +01003936 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
3937 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01003938 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3939 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffiead447b72019-11-18 15:50:22 +01003940 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
3941 (sourceDesc != nullptr &&
3942 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003943 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003944 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003945 return INVALID_OPERATION;
3946 }
Francois Gaffie06e324a2020-10-14 18:02:07 +02003947 if (sourceDesc == nullptr) {
François Gaffiead447b72019-11-18 15:50:22 +01003948 SortedVector<audio_io_handle_t> outputs =
3949 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
3950 // if the sink device is reachable via an opened output stream, request to
3951 // go via this output stream by adding a second source to the patch
3952 // description
3953 output = selectOutput(outputs);
Francois Gaffie06e324a2020-10-14 18:02:07 +02003954 if (output != AUDIO_IO_HANDLE_NONE) {
3955 outputDesc = mOutputs.valueFor(output);
3956 if (outputDesc->isDuplicated()) {
3957 ALOGV("%s output for device %s is duplicated",
3958 __FUNCTION__, sinkDevice->toString().c_str());
3959 return INVALID_OPERATION;
3960 }
François Gaffiead447b72019-11-18 15:50:22 +01003961 }
Francois Gaffie06e324a2020-10-14 18:02:07 +02003962 }
3963 if (outputDesc != nullptr) {
François Gaffiead447b72019-11-18 15:50:22 +01003964 audio_port_config srcMixPortConfig = {};
3965 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
François Gaffiead447b72019-11-18 15:50:22 +01003966 // for volume control, we may need a valid stream
3967 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
3968 sourceDesc->stream() : AUDIO_STREAM_PATCH;
3969 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003970 }
Eric Laurent83b88082014-06-20 18:31:16 -07003971 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003972 }
3973 // TODO: check from routing capabilities in config file and other conflicting patches
3974
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11003975installPatch:
François Gaffiead447b72019-11-18 15:50:22 +01003976 status_t status = installPatch(
3977 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003978 if (status != NO_ERROR) {
François Gaffiead447b72019-11-18 15:50:22 +01003979 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07003980 return INVALID_OPERATION;
3981 }
3982 } else {
3983 return BAD_VALUE;
3984 }
3985 } else {
3986 return BAD_VALUE;
3987 }
3988 return NO_ERROR;
3989}
3990
3991status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3992 uid_t uid)
3993{
3994 ALOGV("releaseAudioPatch() patch %d", handle);
3995
3996 ssize_t index = mAudioPatches.indexOfKey(handle);
3997
3998 if (index < 0) {
3999 return BAD_VALUE;
4000 }
4001 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01004002 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4003 __func__, mUidCached, patchDesc->getUid(), uid);
4004 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004005 return INVALID_OPERATION;
4006 }
François Gaffiead447b72019-11-18 15:50:22 +01004007 return releaseAudioPatchInternal(handle);
4008}
Eric Laurent6a94d692014-05-20 11:18:06 -07004009
François Gaffiead447b72019-11-18 15:50:22 +01004010status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4011 uint32_t delayMs)
4012{
4013 ALOGV("%s patch %d", __func__, handle);
4014 if (mAudioPatches.indexOfKey(handle) < 0) {
4015 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4016 return BAD_VALUE;
4017 }
4018 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004019 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffiead447b72019-11-18 15:50:22 +01004020 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004021 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004022 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004023 if (outputDesc == NULL) {
François Gaffiead447b72019-11-18 15:50:22 +01004024 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004025 return BAD_VALUE;
4026 }
4027
François Gaffie11d30102018-11-02 16:09:09 +01004028 setOutputDevices(outputDesc,
4029 getNewOutputDevices(outputDesc, true /*fromCache*/),
4030 true,
4031 0,
4032 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004033 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4034 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004035 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004036 if (inputDesc == NULL) {
François Gaffiead447b72019-11-18 15:50:22 +01004037 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004038 return BAD_VALUE;
4039 }
4040 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004041 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004042 true,
4043 NULL);
4044 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffiead447b72019-11-18 15:50:22 +01004045 status_t status =
4046 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4047 ALOGV("%s patch panel returned %d patchHandle %d",
4048 __func__, status, patchDesc->getAfHandle());
4049 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004050 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004051 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie3b173542020-04-06 17:39:47 +02004052 // SW Bridge
4053 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4054 sp<SwAudioOutputDescriptor> outputDesc =
4055 mOutputs.getOutputFromId(patch->sources[1].id);
4056 if (outputDesc == NULL) {
Francois Gaffie5bd3d2d2020-05-06 18:37:04 +02004057 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4058 // releaseOutput has already called closeOuput in case of direct output
4059 return NO_ERROR;
Francois Gaffie3b173542020-04-06 17:39:47 +02004060 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004061 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4062 // force SwOutput patch removal as AF counter part patch has already gone.
4063 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4064 removeAudioPatch(outputDesc->getPatchHandle());
4065 }
Francois Gaffie3b173542020-04-06 17:39:47 +02004066 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4067 setOutputDevices(outputDesc,
4068 getNewOutputDevices(outputDesc, true /*fromCache*/),
4069 true, /*force*/
4070 0,
4071 NULL);
4072 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004073 } else {
4074 return BAD_VALUE;
4075 }
4076 } else {
4077 return BAD_VALUE;
4078 }
4079 return NO_ERROR;
4080}
4081
4082status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4083 struct audio_patch *patches,
4084 unsigned int *generation)
4085{
François Gaffie53615e22015-03-19 09:24:12 +01004086 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004087 return BAD_VALUE;
4088 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004089 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004090 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004091}
4092
Eric Laurente1715a42014-05-20 11:30:42 -07004093status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004094{
Eric Laurente1715a42014-05-20 11:30:42 -07004095 ALOGV("setAudioPortConfig()");
4096
4097 if (config == NULL) {
4098 return BAD_VALUE;
4099 }
4100 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4101 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004102 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4103 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004104 }
4105
Eric Laurenta121f902014-06-03 13:32:54 -07004106 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004107 if (config->type == AUDIO_PORT_TYPE_MIX) {
4108 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004109 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004110 if (outputDesc == NULL) {
4111 return BAD_VALUE;
4112 }
Eric Laurent84c70242014-06-23 08:46:27 -07004113 ALOG_ASSERT(!outputDesc->isDuplicated(),
4114 "setAudioPortConfig() called on duplicated output %d",
4115 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004116 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004117 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004118 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004119 if (inputDesc == NULL) {
4120 return BAD_VALUE;
4121 }
Eric Laurenta121f902014-06-03 13:32:54 -07004122 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004123 } else {
4124 return BAD_VALUE;
4125 }
4126 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4127 sp<DeviceDescriptor> deviceDesc;
4128 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4129 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4130 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4131 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4132 } else {
4133 return BAD_VALUE;
4134 }
4135 if (deviceDesc == NULL) {
4136 return BAD_VALUE;
4137 }
Eric Laurenta121f902014-06-03 13:32:54 -07004138 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004139 } else {
4140 return BAD_VALUE;
4141 }
4142
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004143 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004144 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4145 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004146 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004147 audioPortConfig->toAudioPortConfig(&newConfig, config);
4148 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004149 }
Eric Laurenta121f902014-06-03 13:32:54 -07004150 if (status != NO_ERROR) {
4151 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004152 }
Eric Laurente1715a42014-05-20 11:30:42 -07004153
4154 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004155}
4156
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004157void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4158{
Eric Laurentd60560a2015-04-10 11:31:20 -07004159 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004160 clearAudioPatches(uid);
4161 clearSessionRoutes(uid);
4162}
4163
Eric Laurent6a94d692014-05-20 11:18:06 -07004164void AudioPolicyManager::clearAudioPatches(uid_t uid)
4165{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004166 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004167 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffiead447b72019-11-18 15:50:22 +01004168 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004169 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004170 }
4171 }
4172}
4173
François Gaffiec005e562018-11-06 15:04:49 +01004174void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004175{
François Gaffiec005e562018-11-06 15:04:49 +01004176 // Take the first attributes following the product strategy as it is used to retrieve the routed
4177 // device. All attributes wihin a strategy follows the same "routing strategy"
4178 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4179 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004180 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004181 for (size_t j = 0; j < mOutputs.size(); j++) {
4182 if (mOutputs.keyAt(j) == ouptutToSkip) {
4183 continue;
4184 }
4185 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004186 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004187 continue;
4188 }
4189 // If the default device for this strategy is on another output mix,
4190 // invalidate all tracks in this strategy to force re connection.
4191 // Otherwise select new device on the output mix.
4192 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004193 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4194 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004195 }
4196 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004197 setOutputDevices(
4198 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004199 }
4200 }
4201}
4202
4203void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4204{
4205 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004206 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004207 for (size_t i = 0; i < mOutputs.size(); i++) {
4208 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004209 for (const auto& client : outputDesc->getClientIterable()) {
4210 if (client->hasPreferredDevice() && client->uid() == uid) {
4211 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004212 auto clientStrategy = client->strategy();
4213 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4214 end(affectedStrategies)) {
4215 continue;
4216 }
4217 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004218 }
4219 }
4220 }
4221 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004222 for (const auto& strategy : affectedStrategies) {
4223 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004224 }
4225
4226 // remove input routes associated with this uid
4227 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004228 for (size_t i = 0; i < mInputs.size(); i++) {
4229 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004230 for (const auto& client : inputDesc->getClientIterable()) {
4231 if (client->hasPreferredDevice() && client->uid() == uid) {
4232 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4233 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004234 }
4235 }
4236 }
4237 // reroute inputs if necessary
4238 SortedVector<audio_io_handle_t> inputsToClose;
4239 for (size_t i = 0; i < mInputs.size(); i++) {
4240 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004241 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004242 inputsToClose.add(inputDesc->mIoHandle);
4243 }
4244 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004245 for (const auto& input : inputsToClose) {
4246 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004247 }
4248}
4249
Eric Laurentd60560a2015-04-10 11:31:20 -07004250void AudioPolicyManager::clearAudioSources(uid_t uid)
4251{
4252 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004253 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4254 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004255 stopAudioSource(mAudioSources.keyAt(i));
4256 }
4257 }
4258}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004259
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004260status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4261 audio_io_handle_t *ioHandle,
4262 audio_devices_t *device)
4263{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004264 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4265 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004266 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004267 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004268
François Gaffiedf372692015-03-19 10:43:27 +01004269 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004270}
4271
Eric Laurentd60560a2015-04-10 11:31:20 -07004272status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004273 const audio_attributes_t *attributes,
4274 audio_port_handle_t *portId,
4275 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004276{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004277 ALOGV("%s", __FUNCTION__);
4278 *portId = AUDIO_PORT_HANDLE_NONE;
4279
4280 if (source == NULL || attributes == NULL || portId == NULL) {
4281 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4282 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004283 return BAD_VALUE;
4284 }
4285
Eric Laurentd60560a2015-04-10 11:31:20 -07004286 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4287 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004288 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4289 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004290 return INVALID_OPERATION;
4291 }
4292
François Gaffie11d30102018-11-02 16:09:09 +01004293 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004294 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004295 String8(source->ext.device.address),
4296 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004297 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004298 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004299 return BAD_VALUE;
4300 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004301
jiabindff2a4f2019-09-10 14:29:54 -07004302 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004303
François Gaffieaaac0fd2018-11-22 17:56:39 +01004304 sp<SourceClientDescriptor> sourceDesc =
François Gaffiead447b72019-11-18 15:50:22 +01004305 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004306 mEngine->getStreamTypeForAttributes(*attributes),
4307 mEngine->getProductStrategyForAttributes(*attributes),
4308 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004309
4310 status_t status = connectAudioSource(sourceDesc);
4311 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004312 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004313 }
4314 return status;
4315}
4316
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004317status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004318{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004319 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004320
4321 // make sure we only have one patch per source.
4322 disconnectAudioSource(sourceDesc);
4323
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004324 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffied2c073b2020-09-29 16:05:07 +02004325 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4326 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4327 sourceDesc->srcDevice()->type(),
4328 String8(sourceDesc->srcDevice()->address().c_str()),
4329 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004330 DeviceVector sinkDevices =
Francois Gaffie5bd3d2d2020-05-06 18:37:04 +02004331 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004332 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004333 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffied2c073b2020-09-29 16:05:07 +02004334 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4335 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4336 return INVALID_OPERATION;
4337 }
François Gaffiead447b72019-11-18 15:50:22 +01004338 PatchBuilder patchBuilder;
4339 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4340 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4341 status_t status =
4342 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4343 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4344 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4345 return INVALID_OPERATION;
4346 }
Francois Gaffied2c073b2020-09-29 16:05:07 +02004347 sourceDesc->connect(handle, sinkDevice);
François Gaffiead447b72019-11-18 15:50:22 +01004348 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4349 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4350 if (swOutput != 0) {
4351 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004352 if (status != NO_ERROR) {
François Gaffiead447b72019-11-18 15:50:22 +01004353 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004354 }
François Gaffiead447b72019-11-18 15:50:22 +01004355 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004356 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffiead447b72019-11-18 15:50:22 +01004357 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004358 }
François Gaffiead447b72019-11-18 15:50:22 +01004359 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004360 uint32_t delayMs = 0;
François Gaffiead447b72019-11-18 15:50:22 +01004361 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004362 if (status != NO_ERROR) {
François Gaffiead447b72019-11-18 15:50:22 +01004363 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4364 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004365 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004366 if (delayMs != 0) {
4367 usleep(delayMs * 1000);
4368 }
François Gaffiead447b72019-11-18 15:50:22 +01004369 } else {
4370 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4371 if (hwOutputDesc != 0) {
4372 // create Hwoutput and add to mHwOutputs
4373 } else {
4374 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4375 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004376 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004377 return NO_ERROR;
François Gaffiead447b72019-11-18 15:50:22 +01004378
4379FailureSourceActive:
4380 swOutput->stop();
4381 releaseOutput(sourceDesc->portId());
4382FailureSourceAdded:
4383 sourceDesc->setSwOutput(nullptr);
4384FailureReleasePatch:
4385 releaseAudioPatchInternal(handle);
4386 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004387}
4388
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004389status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004390{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004391 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4392 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004393 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004394 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004395 return BAD_VALUE;
4396 }
4397 status_t status = disconnectAudioSource(sourceDesc);
4398
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004399 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004400 return status;
4401}
4402
Andy Hung2ddee192015-12-18 17:34:44 -08004403status_t AudioPolicyManager::setMasterMono(bool mono)
4404{
4405 if (mMasterMono == mono) {
4406 return NO_ERROR;
4407 }
4408 mMasterMono = mono;
4409 // if enabling mono we close all offloaded devices, which will invalidate the
4410 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4411 // for recreating the new AudioTrack as non-offloaded PCM.
4412 //
4413 // If disabling mono, we leave all tracks as is: we don't know which clients
4414 // and tracks are able to be recreated as offloaded. The next "song" should
4415 // play back offloaded.
4416 if (mMasterMono) {
4417 Vector<audio_io_handle_t> offloaded;
4418 for (size_t i = 0; i < mOutputs.size(); ++i) {
4419 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4420 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4421 offloaded.push(desc->mIoHandle);
4422 }
4423 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004424 for (const auto& handle : offloaded) {
4425 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004426 }
4427 }
4428 // update master mono for all remaining outputs
4429 for (size_t i = 0; i < mOutputs.size(); ++i) {
4430 updateMono(mOutputs.keyAt(i));
4431 }
4432 return NO_ERROR;
4433}
4434
4435status_t AudioPolicyManager::getMasterMono(bool *mono)
4436{
4437 *mono = mMasterMono;
4438 return NO_ERROR;
4439}
4440
Eric Laurentac9cef52017-06-09 15:46:26 -07004441float AudioPolicyManager::getStreamVolumeDB(
4442 audio_stream_type_t stream, int index, audio_devices_t device)
4443{
jiabin12dc6b02019-10-01 09:38:30 -07004444 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004445}
4446
jiabin81772902018-04-02 17:52:27 -07004447status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4448 audio_format_t *surroundFormats,
4449 bool *surroundFormatsEnabled,
4450 bool reported)
4451{
4452 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
4453 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
4454 return BAD_VALUE;
4455 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004456 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
4457 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07004458
4459 size_t formatsWritten = 0;
4460 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004461 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07004462 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004463 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07004464 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08004465 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4466 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4467 FormatVector supportedFormats =
4468 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
4469 for (size_t j = 0; j < supportedFormats.size(); j++) {
4470 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
4471 formats.insert(supportedFormats[j]);
4472 } else {
4473 for (const auto& pair : mConfig.getSurroundFormats()) {
4474 if (pair.second.count(supportedFormats[j]) != 0) {
4475 formats.insert(pair.first);
4476 break;
4477 }
4478 }
4479 }
4480 }
jiabin81772902018-04-02 17:52:27 -07004481 }
4482 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004483 for (const auto& pair : mConfig.getSurroundFormats()) {
4484 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07004485 }
4486 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004487 *numSurroundFormats = formats.size();
4488 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4489 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07004490 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07004491 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07004492 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004493 bool formatEnabled = true;
4494 switch (forceUse) {
4495 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
4496 formatEnabled = mManualSurroundFormats.count(format) != 0;
4497 break;
4498 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4499 formatEnabled = false;
4500 break;
4501 default: // AUTO or ALWAYS => true
4502 break;
jiabin81772902018-04-02 17:52:27 -07004503 }
4504 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4505 }
jiabin81772902018-04-02 17:52:27 -07004506 }
4507 return NO_ERROR;
4508}
4509
4510status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4511{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004512 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004513 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4514 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004515 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004516 return BAD_VALUE;
4517 }
4518
Mikhail Naganov100f0122018-11-29 11:22:16 -08004519 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4520 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004521 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004522 return INVALID_OPERATION;
4523 }
4524
Mikhail Naganov100f0122018-11-29 11:22:16 -08004525 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004526 return NO_ERROR;
4527 }
4528
Mikhail Naganov100f0122018-11-29 11:22:16 -08004529 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004530 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004531 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004532 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004533 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004534 }
4535 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004536 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004537 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004538 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004539 }
4540 }
4541
4542 sp<SwAudioOutputDescriptor> outputDesc;
4543 bool profileUpdated = false;
jiabin12dc6b02019-10-01 09:38:30 -07004544 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4545 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004546 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4547 // Simulate reconnection to update enabled surround sound formats.
jiabin6713a382019-09-12 16:29:15 -07004548 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabineaf09f02019-08-19 15:08:30 -07004549 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004550 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4551 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4552 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004553 name.c_str(),
4554 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004555 if (status != NO_ERROR) {
4556 continue;
4557 }
4558 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4559 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4560 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004561 name.c_str(),
4562 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004563 profileUpdated |= (status == NO_ERROR);
4564 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004565 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin12dc6b02019-10-01 09:38:30 -07004566 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004567 AUDIO_DEVICE_IN_HDMI);
4568 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4569 // Simulate reconnection to update enabled surround sound formats.
jiabin6713a382019-09-12 16:29:15 -07004570 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabineaf09f02019-08-19 15:08:30 -07004571 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004572 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4573 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4574 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004575 name.c_str(),
4576 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004577 if (status != NO_ERROR) {
4578 continue;
4579 }
4580 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4581 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4582 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004583 name.c_str(),
4584 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004585 profileUpdated |= (status == NO_ERROR);
4586 }
4587
jiabin81772902018-04-02 17:52:27 -07004588 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004589 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004590 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004591 }
4592
4593 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4594}
4595
Eric Laurent5ada82e2019-08-29 17:53:54 -07004596void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004597{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004598 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004599 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004600 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004601 }
4602}
4603
jiabin6012f912018-11-02 17:06:30 -07004604bool AudioPolicyManager::isHapticPlaybackSupported()
4605{
4606 for (const auto& hwModule : mHwModules) {
4607 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4608 for (const auto &outProfile : outputProfiles) {
4609 struct audio_port audioPort;
4610 outProfile->toAudioPort(&audioPort);
4611 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4612 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4613 return true;
4614 }
4615 }
4616 }
4617 }
4618 return false;
4619}
4620
Eric Laurent8340e672019-11-06 11:01:08 -08004621bool AudioPolicyManager::isCallScreenModeSupported()
4622{
4623 return getConfig().isCallScreenModeSupported();
4624}
4625
4626
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004627status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004628{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004629 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffied2c073b2020-09-29 16:05:07 +02004630 if (!sourceDesc->isConnected()) {
4631 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
4632 return NO_ERROR;
4633 }
François Gaffiead447b72019-11-18 15:50:22 +01004634 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4635 if (swOutput != 0) {
4636 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004637 if (status == NO_ERROR) {
François Gaffiead447b72019-11-18 15:50:22 +01004638 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004639 }
François Gaffiead447b72019-11-18 15:50:22 +01004640 releaseOutput(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004641 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004642 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004643 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004644 // close Hwoutput and remove from mHwOutputs
4645 } else {
4646 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4647 }
4648 }
Francois Gaffied2c073b2020-09-29 16:05:07 +02004649 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
4650 sourceDesc->disconnect();
4651 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07004652}
4653
François Gaffiec005e562018-11-06 15:04:49 +01004654sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4655 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004656{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004657 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004658 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004659 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004660 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004661 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4662 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004663 source = sourceDesc;
4664 break;
4665 }
4666 }
4667 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004668}
4669
Eric Laurente552edb2014-03-10 17:42:56 -07004670// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004671// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004672// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004673uint32_t AudioPolicyManager::nextAudioPortGeneration()
4674{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004675 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004676}
4677
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004678static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov8916ae92020-10-21 13:04:58 -07004679 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
4680 !audioPolicyXmlConfigFile.empty()) {
4681 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
4682 if (ret == NO_ERROR) {
4683 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08004684 }
Mikhail Naganov8916ae92020-10-21 13:04:58 -07004685 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07004686 }
Mikhail Naganov8916ae92020-10-21 13:04:58 -07004687 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004688}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004689
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004690AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4691 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004692 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004693 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004694 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004695 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004696 mA2dpSuspended(false),
Mikhail Naganov560095b2020-03-05 16:28:57 -08004697 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004698 mAudioPortGeneration(1),
4699 mBeaconMuteRefCount(0),
4700 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004701 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004702 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004703 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004704 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004705{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004706}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004707
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004708AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4709 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4710{
4711 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004712}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004713
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004714void AudioPolicyManager::loadConfig() {
4715 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004716 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004717 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004718 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004719}
4720
4721status_t AudioPolicyManager::initialize() {
Mikhail Naganove13c6792019-05-14 10:32:51 -07004722 {
4723 auto engLib = EngineLibrary::load(
4724 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
4725 if (!engLib) {
4726 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
4727 return NO_INIT;
4728 }
4729 mEngine = engLib->createEngine();
4730 if (mEngine == nullptr) {
4731 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
4732 return NO_INIT;
4733 }
François Gaffie2110e042015-03-24 08:41:51 +01004734 }
4735 mEngine->setObserver(this);
4736 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004737 if (status != NO_ERROR) {
4738 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4739 return status;
4740 }
François Gaffie2110e042015-03-24 08:41:51 +01004741
Mikhail Naganov560095b2020-03-05 16:28:57 -08004742 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07004743 // open all output streams needed to access attached devices
Mikhail Naganova30ec142020-03-24 09:32:34 -07004744 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01004745
Eric Laurent3a4311c2014-03-17 12:00:47 -07004746 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004747 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4748 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4749 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004750 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004751 }
jiabin9ff780e2018-03-19 18:19:52 -07004752 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07004753 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabin6713a382019-09-12 16:29:15 -07004754 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004755 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabin6713a382019-09-12 16:29:15 -07004756 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004757 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabin6713a382019-09-12 16:29:15 -07004758 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004759 }
4760 }
4761 }
Eric Laurente552edb2014-03-10 17:42:56 -07004762
Francois Gaffiefa51ed72020-10-14 16:13:20 +02004763 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07004764
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004765 // Silence ALOGV statements
4766 property_set("log.tag." LOG_TAG, "D");
4767
Eric Laurentcca11ce2020-11-25 15:31:27 +01004768 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
4769 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
4770
Eric Laurente552edb2014-03-10 17:42:56 -07004771 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004772 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004773}
4774
Eric Laurente0720872014-03-11 09:30:41 -07004775AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004776{
Eric Laurente552edb2014-03-10 17:42:56 -07004777 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004778 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004779 }
4780 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004781 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004782 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004783 mAvailableOutputDevices.clear();
4784 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004785 mOutputs.clear();
4786 mInputs.clear();
4787 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004788 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004789 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004790}
4791
Eric Laurente0720872014-03-11 09:30:41 -07004792status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004793{
Eric Laurent87ffa392015-05-22 10:32:38 -07004794 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004795}
4796
Eric Laurente552edb2014-03-10 17:42:56 -07004797// ---
4798
Mikhail Naganov560095b2020-03-05 16:28:57 -08004799void AudioPolicyManager::onNewAudioModulesAvailable()
4800{
Mikhail Naganova30ec142020-03-24 09:32:34 -07004801 DeviceVector newDevices;
4802 onNewAudioModulesAvailableInt(&newDevices);
4803 if (!newDevices.empty()) {
4804 nextAudioPortGeneration();
4805 mpClientInterface->onAudioPortListUpdate();
4806 }
4807}
4808
4809void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
4810{
Mikhail Naganov560095b2020-03-05 16:28:57 -08004811 for (const auto& hwModule : mHwModulesAll) {
4812 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
4813 continue;
4814 }
4815 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
4816 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4817 ALOGW("could not open HW module %s", hwModule->getName());
4818 continue;
4819 }
4820 mHwModules.push_back(hwModule);
4821 // open all output streams needed to access attached devices
4822 // except for direct output streams that are only opened when they are actually
4823 // required by an app.
4824 // This also validates mAvailableOutputDevices list
4825 for (const auto& outProfile : hwModule->getOutputProfiles()) {
4826 if (!outProfile->canOpenNewIo()) {
4827 ALOGE("Invalid Output profile max open count %u for profile %s",
4828 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4829 continue;
4830 }
4831 if (!outProfile->hasSupportedDevices()) {
4832 ALOGW("Output profile contains no device on module %s", hwModule->getName());
4833 continue;
4834 }
4835 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
4836 mTtsOutputAvailable = true;
4837 }
4838
Mikhail Naganov560095b2020-03-05 16:28:57 -08004839 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4840 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
4841 sp<DeviceDescriptor> supportedDevice = 0;
4842 if (supportedDevices.contains(mDefaultOutputDevice)) {
4843 supportedDevice = mDefaultOutputDevice;
4844 } else {
4845 // choose first device present in profile's SupportedDevices also part of
4846 // mAvailableOutputDevices.
4847 if (availProfileDevices.isEmpty()) {
4848 continue;
4849 }
4850 supportedDevice = availProfileDevices.itemAt(0);
4851 }
4852 if (!mOutputDevicesAll.contains(supportedDevice)) {
4853 continue;
4854 }
4855 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4856 mpClientInterface);
4857 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4858 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4859 AUDIO_STREAM_DEFAULT,
4860 AUDIO_OUTPUT_FLAG_NONE, &output);
4861 if (status != NO_ERROR) {
4862 ALOGW("Cannot open output stream for devices %s on hw module %s",
4863 supportedDevice->toString().c_str(), hwModule->getName());
4864 continue;
4865 }
4866 for (const auto &device : availProfileDevices) {
4867 // give a valid ID to an attached device once confirmed it is reachable
4868 if (!device->isAttached()) {
4869 device->attach(hwModule);
4870 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07004871 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganova30ec142020-03-24 09:32:34 -07004872 if (newDevices) newDevices->add(device);
Mikhail Naganov560095b2020-03-05 16:28:57 -08004873 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4874 }
4875 }
Francois Gaffiefa51ed72020-10-14 16:13:20 +02004876 if (mPrimaryOutput == nullptr &&
Mikhail Naganov560095b2020-03-05 16:28:57 -08004877 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4878 mPrimaryOutput = outputDesc;
4879 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004880 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
4881 outputDesc->close();
4882 } else {
4883 addOutput(output, outputDesc);
4884 setOutputDevices(outputDesc,
4885 DeviceVector(supportedDevice),
4886 true,
4887 0,
4888 NULL);
4889 }
Mikhail Naganov560095b2020-03-05 16:28:57 -08004890 }
4891 // open input streams needed to access attached devices to validate
4892 // mAvailableInputDevices list
4893 for (const auto& inProfile : hwModule->getInputProfiles()) {
4894 if (!inProfile->canOpenNewIo()) {
4895 ALOGE("Invalid Input profile max open count %u for profile %s",
4896 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4897 continue;
4898 }
4899 if (!inProfile->hasSupportedDevices()) {
4900 ALOGW("Input profile contains no device on module %s", hwModule->getName());
4901 continue;
4902 }
4903 // chose first device present in profile's SupportedDevices also part of
4904 // available input devices
4905 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4906 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
4907 if (availProfileDevices.isEmpty()) {
4908 ALOGE("%s: Input device list is empty!", __FUNCTION__);
4909 continue;
4910 }
4911 sp<AudioInputDescriptor> inputDesc =
4912 new AudioInputDescriptor(inProfile, mpClientInterface);
4913
4914 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
4915 status_t status = inputDesc->open(nullptr,
4916 availProfileDevices.itemAt(0),
4917 AUDIO_SOURCE_MIC,
4918 AUDIO_INPUT_FLAG_NONE,
4919 &input);
4920 if (status != NO_ERROR) {
4921 ALOGW("Cannot open input stream for device %s on hw module %s",
4922 availProfileDevices.toString().c_str(),
4923 hwModule->getName());
4924 continue;
4925 }
4926 for (const auto &device : availProfileDevices) {
4927 // give a valid ID to an attached device once confirmed it is reachable
4928 if (!device->isAttached()) {
4929 device->attach(hwModule);
4930 device->importAudioPortAndPickAudioProfile(inProfile, true);
4931 mAvailableInputDevices.add(device);
Mikhail Naganova30ec142020-03-24 09:32:34 -07004932 if (newDevices) newDevices->add(device);
Mikhail Naganov560095b2020-03-05 16:28:57 -08004933 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4934 }
4935 }
4936 inputDesc->close();
4937 }
4938 }
4939}
4940
Eric Laurent98e38192018-02-15 18:31:53 -08004941void AudioPolicyManager::addOutput(audio_io_handle_t output,
4942 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004943{
Eric Laurent1c333e22014-05-20 10:48:17 -07004944 mOutputs.add(output, outputDesc);
jiabin12dc6b02019-10-01 09:38:30 -07004945 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004946 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004947 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004948 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004949}
4950
François Gaffie53615e22015-03-19 09:24:12 +01004951void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4952{
Francois Gaffiefa51ed72020-10-14 16:13:20 +02004953 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
4954 ALOGV("%s: removing primary output", __func__);
4955 mPrimaryOutput = nullptr;
4956 }
François Gaffie53615e22015-03-19 09:24:12 +01004957 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004958 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004959}
4960
Eric Laurent98e38192018-02-15 18:31:53 -08004961void AudioPolicyManager::addInput(audio_io_handle_t input,
4962 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004963{
Eric Laurent1c333e22014-05-20 10:48:17 -07004964 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004965 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004966}
Eric Laurente552edb2014-03-10 17:42:56 -07004967
François Gaffie11d30102018-11-02 16:09:09 +01004968status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004969 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004970 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004971{
François Gaffie11d30102018-11-02 16:09:09 +01004972 audio_devices_t deviceType = device->type();
jiabin6713a382019-09-12 16:29:15 -07004973 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07004974 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004975
François Gaffie11d30102018-11-02 16:09:09 +01004976 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004977 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004978 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004979 }
Eric Laurente552edb2014-03-10 17:42:56 -07004980
Eric Laurent3b73df72014-03-11 09:06:29 -07004981 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004982 // first list already open outputs that can be routed to this device
4983 for (size_t i = 0; i < mOutputs.size(); i++) {
4984 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004985 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin12dc6b02019-10-01 09:38:30 -07004986 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01004987 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4988 mOutputs.keyAt(i), device->toString().c_str());
4989 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004990 }
4991 }
4992 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004993 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004994 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004995 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4996 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004997 if (profile->supportsDevice(device)) {
4998 profiles.add(profile);
4999 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5000 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005001 }
5002 }
5003 }
5004
Eric Laurent7b279bb2015-12-14 10:18:23 -08005005 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005006
Eric Laurente552edb2014-03-10 17:42:56 -07005007 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005008 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005009 return BAD_VALUE;
5010 }
5011
5012 // open outputs for matching profiles if needed. Direct outputs are also opened to
5013 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5014 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005015 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005016
5017 // nothing to do if one output is already opened for this profile
5018 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005019 for (j = 0; j < outputs.size(); j++) {
5020 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005021 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005022 // matching profile: save the sample rates, format and channel masks supported
5023 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005024 if (audio_device_is_digital(deviceType)) {
jiabindff2a4f2019-09-10 14:29:54 -07005025 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005026 }
Eric Laurente552edb2014-03-10 17:42:56 -07005027 break;
5028 }
5029 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005030 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005031 continue;
5032 }
5033
Eric Laurent3974e3b2017-12-07 17:58:43 -08005034 if (!profile->canOpenNewIo()) {
5035 ALOGW("Max Output number %u already opened for this profile %s",
5036 profile->maxOpenCount, profile->getTagName().c_str());
5037 continue;
5038 }
5039
Eric Laurent83efe1c2017-07-09 16:51:08 -07005040 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabineaf09f02019-08-19 15:08:30 -07005041 deviceType, address.string(), profile.get(), profile->getName().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005042 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005043 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01005044 status_t status = desc->open(nullptr, DeviceVector(device),
Eric Laurentfe231122017-11-17 17:48:06 -08005045 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07005046
Eric Laurentfe231122017-11-17 17:48:06 -08005047 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07005048 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07005049 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005050 char *param = audio_device_address_to_parameter(deviceType, address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005051 mpClientInterface->setParameters(output, String8(param));
5052 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07005053 }
François Gaffie11d30102018-11-02 16:09:09 +01005054 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005055 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005056 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005057 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005058 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01005059 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08005060 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08005061 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005062 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5063 profile->pickAudioProfile(
5064 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005065 config.offload_info.sample_rate = config.sample_rate;
5066 config.offload_info.channel_mask = config.channel_mask;
5067 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08005068
François Gaffie11d30102018-11-02 16:09:09 +01005069 status_t status = desc->open(&config, DeviceVector(device),
5070 AUDIO_STREAM_DEFAULT,
Eric Laurentfe231122017-11-17 17:48:06 -08005071 AUDIO_OUTPUT_FLAG_NONE, &output);
5072 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07005073 output = AUDIO_IO_HANDLE_NONE;
5074 }
Eric Laurentd4692962014-05-05 18:13:44 -07005075 }
5076
Eric Laurentcf2c0212014-07-25 16:20:43 -07005077 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07005078 addOutput(output, desc);
Eric Laurent0e26e3f2020-04-29 14:24:16 -07005079 if (audio_is_remote_submix_device(deviceType) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01005080 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07005081 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix)
5082 == NO_ERROR) {
François Gaffieb141c522018-03-12 11:47:40 +01005083 policyMix->setOutput(desc);
Mikhail Naganovbfac5832019-03-05 16:55:28 -08005084 desc->mPolicyMix = policyMix;
François Gaffieb141c522018-03-12 11:47:40 +01005085 } else {
5086 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Eric Laurent275e8e92014-11-30 15:14:47 -08005087 address.string());
5088 }
François Gaffie036e1e92015-03-19 10:16:24 +01005089
Eric Laurent87ffa392015-05-22 10:32:38 -07005090 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
5091 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08005092 // no duplicated output for direct outputs and
5093 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07005094 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07005095
Eric Laurentd4692962014-05-05 18:13:44 -07005096 //TODO: configure audio effect output stage here
5097
5098 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08005099 sp<SwAudioOutputDescriptor> dupOutputDesc =
5100 new SwAudioOutputDescriptor(NULL, mpClientInterface);
5101 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
5102 &duplicatedOutput);
5103 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07005104 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07005105 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07005106 } else {
5107 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005108 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08005109 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01005110 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07005111 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005112 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005113 }
Eric Laurente552edb2014-03-10 17:42:56 -07005114 }
Francois Gaffiefa51ed72020-10-14 16:13:20 +02005115 if (mPrimaryOutput == nullptr
5116 && (profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
5117 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
5118 mPrimaryOutput = desc;
5119 }
Eric Laurente552edb2014-03-10 17:42:56 -07005120 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07005121 } else {
5122 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07005123 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07005124 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005125 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005126 profiles.removeAt(profile_index);
5127 profile_index--;
5128 } else {
5129 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005130 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005131 if (audio_device_is_digital(deviceType)) {
jiabindff2a4f2019-09-10 14:29:54 -07005132 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005133 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005134
François Gaffie11d30102018-11-02 16:09:09 +01005135 if (device_distinguishes_on_address(deviceType)) {
5136 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5137 device->toString().c_str());
5138 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5139 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005140 }
Eric Laurente552edb2014-03-10 17:42:56 -07005141 ALOGV("checkOutputsForDevice(): adding output %d", output);
5142 }
5143 }
5144
5145 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005146 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005147 return BAD_VALUE;
5148 }
Eric Laurentd4692962014-05-05 18:13:44 -07005149 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005150 // check if one opened output is not needed any more after disconnecting one device
5151 for (size_t i = 0; i < mOutputs.size(); i++) {
5152 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005153 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005154 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005155 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
jiabin12dc6b02019-10-01 09:38:30 -07005156 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005157 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005158 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005159 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5160 mOutputs.keyAt(i));
5161 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005162 }
Eric Laurente552edb2014-03-10 17:42:56 -07005163 }
5164 }
Eric Laurentd4692962014-05-05 18:13:44 -07005165 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005166 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005167 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5168 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005169 if (profile->supportsDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07005170 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08005171 "clearing direct output profile %zu on module %s",
5172 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005173 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07005174 }
5175 }
5176 }
5177 }
5178 return NO_ERROR;
5179}
5180
François Gaffie11d30102018-11-02 16:09:09 +01005181status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005182 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005183{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005184 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005185
François Gaffie11d30102018-11-02 16:09:09 +01005186 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005187 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005188 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005189 }
5190
Eric Laurentd4692962014-05-05 18:13:44 -07005191 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005192 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005193 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005194 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005195 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005196 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005197 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005198 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005199
François Gaffie11d30102018-11-02 16:09:09 +01005200 if (profile->supportsDevice(device)) {
5201 profiles.add(profile);
5202 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5203 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005204 }
5205 }
5206 }
5207
Eric Laurent0dd51852019-04-19 18:18:58 -07005208 if (profiles.isEmpty()) {
5209 ALOGW("%s: No input profile available for device %s",
5210 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005211 return BAD_VALUE;
5212 }
5213
5214 // open inputs for matching profiles if needed. Direct inputs are also opened to
5215 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5216 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5217
Eric Laurent1c333e22014-05-20 10:48:17 -07005218 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005219
Eric Laurentd4692962014-05-05 18:13:44 -07005220 // nothing to do if one input is already opened for this profile
5221 size_t input_index;
5222 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5223 desc = mInputs.valueAt(input_index);
5224 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005225 if (audio_device_is_digital(device->type())) {
jiabindff2a4f2019-09-10 14:29:54 -07005226 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005227 }
Eric Laurentd4692962014-05-05 18:13:44 -07005228 break;
5229 }
5230 }
5231 if (input_index != mInputs.size()) {
5232 continue;
5233 }
5234
Eric Laurent3974e3b2017-12-07 17:58:43 -08005235 if (!profile->canOpenNewIo()) {
5236 ALOGW("Max Input number %u already opened for this profile %s",
5237 profile->maxOpenCount, profile->getTagName().c_str());
5238 continue;
5239 }
5240
Eric Laurentfe231122017-11-17 17:48:06 -08005241 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005242 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005243 status_t status = desc->open(nullptr,
5244 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005245 AUDIO_SOURCE_MIC,
5246 AUDIO_INPUT_FLAG_NONE,
5247 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005248
Eric Laurentcf2c0212014-07-25 16:20:43 -07005249 if (status == NO_ERROR) {
jiabin6713a382019-09-12 16:29:15 -07005250 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005251 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005252 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005253 mpClientInterface->setParameters(input, String8(param));
5254 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005255 }
François Gaffie11d30102018-11-02 16:09:09 +01005256 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005257 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005258 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005259 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005260 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005261 }
5262
Eric Laurent0dd51852019-04-19 18:18:58 -07005263 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005264 addInput(input, desc);
5265 }
5266 } // endif input != 0
5267
Eric Laurentcf2c0212014-07-25 16:20:43 -07005268 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005269 ALOGW("%s could not open input for device %s", __func__,
5270 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005271 profiles.removeAt(profile_index);
5272 profile_index--;
5273 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005274 if (audio_device_is_digital(device->type())) {
jiabindff2a4f2019-09-10 14:29:54 -07005275 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005276 }
Eric Laurentd4692962014-05-05 18:13:44 -07005277 ALOGV("checkInputsForDevice(): adding input %d", input);
5278 }
5279 } // end scan profiles
5280
5281 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005282 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005283 return BAD_VALUE;
5284 }
5285 } else {
5286 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005287 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005288 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005289 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005290 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005291 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005292 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005293 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005294 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5295 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005296 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005297 }
5298 }
5299 }
5300 } // end disconnect
5301
5302 return NO_ERROR;
5303}
5304
5305
Eric Laurente0720872014-03-11 09:30:41 -07005306void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005307{
5308 ALOGV("closeOutput(%d)", output);
5309
François Gaffie1c878552018-11-22 16:53:21 +01005310 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5311 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005312 ALOGW("closeOutput() unknown output %d", output);
5313 return;
5314 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005315 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005316 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005317
Eric Laurente552edb2014-03-10 17:42:56 -07005318 // look for duplicated outputs connected to the output being removed.
5319 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005320 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5321 if (dupOutput->isDuplicated() &&
5322 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5323 sp<SwAudioOutputDescriptor> remainingOutput =
5324 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005325 // As all active tracks on duplicated output will be deleted,
5326 // and as they were also referenced on the other output, the reference
5327 // count for their stream type must be adjusted accordingly on
5328 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005329 const bool wasActive = remainingOutput->isActive();
5330 // Note: no-op on the closing output where all clients has already been set inactive
5331 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005332 // stop() will be a no op if the output is still active but is needed in case all
5333 // active streams refcounts where cleared above
5334 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005335 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005336 }
Eric Laurente552edb2014-03-10 17:42:56 -07005337 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5338 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5339
5340 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005341 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005342 }
5343 }
5344
Eric Laurent05b90f82014-08-27 15:32:29 -07005345 nextAudioPortGeneration();
5346
François Gaffie1c878552018-11-22 16:53:21 +01005347 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005348 if (index >= 0) {
5349 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005350 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5351 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005352 mAudioPatches.removeItemsAt(index);
5353 mpClientInterface->onAudioPatchListUpdate();
5354 }
5355
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005356 if (closingOutputWasActive) {
5357 closingOutput->stop();
5358 }
François Gaffie1c878552018-11-22 16:53:21 +01005359 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005360
François Gaffie53615e22015-03-19 09:24:12 +01005361 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005362 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005363
5364 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5365 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005366 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005367 bool directOutputOpen = false;
5368 for (size_t i = 0; i < mOutputs.size(); i++) {
5369 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5370 directOutputOpen = true;
5371 break;
5372 }
5373 }
5374 if (!directOutputOpen) {
Michael Chanb7637e92020-12-08 15:44:49 +11005375 ALOGV("no direct outputs open, reset MSD patches");
5376 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5377 // how output devices for patching are resolved. Avoid by caching and reusing the
5378 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5379 // devices to patch to. This may be complicated by the fact that devices may become
5380 // unavailable.
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11005381 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005382 }
5383 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005384}
5385
5386void AudioPolicyManager::closeInput(audio_io_handle_t input)
5387{
5388 ALOGV("closeInput(%d)", input);
5389
5390 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5391 if (inputDesc == NULL) {
5392 ALOGW("closeInput() unknown input %d", input);
5393 return;
5394 }
5395
Eric Laurent6a94d692014-05-20 11:18:06 -07005396 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005397
François Gaffie11d30102018-11-02 16:09:09 +01005398 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005399 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005400 if (index >= 0) {
5401 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005402 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5403 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005404 mAudioPatches.removeItemsAt(index);
5405 mpClientInterface->onAudioPatchListUpdate();
5406 }
5407
Eric Laurentfe231122017-11-17 17:48:06 -08005408 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005409 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005410
François Gaffie11d30102018-11-02 16:09:09 +01005411 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5412 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005413 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005414 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005415 }
Eric Laurente552edb2014-03-10 17:42:56 -07005416}
5417
François Gaffie11d30102018-11-02 16:09:09 +01005418SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5419 const DeviceVector &devices,
5420 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005421{
5422 SortedVector<audio_io_handle_t> outputs;
5423
François Gaffie11d30102018-11-02 16:09:09 +01005424 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005425 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005426 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005427 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005428 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005429 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin12dc6b02019-10-01 09:38:30 -07005430 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005431 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005432 outputs.add(openOutputs.keyAt(i));
5433 }
5434 }
5435 return outputs;
5436}
5437
Mikhail Naganov37977152018-07-11 15:54:44 -07005438void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5439{
5440 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5441 // output is suspended before any tracks are moved to it
5442 checkA2dpSuspend();
5443 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005444 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005445 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005446 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005447 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chanb7637e92020-12-08 15:44:49 +11005448 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
5449 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
5450 // configuration changes will ultimately be rerouted correctly. We can still avoid
5451 // unnecessary rerouting by caching and reusing the arguments to
5452 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
5453 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley5cbec5a2021-02-10 16:02:23 +11005454 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005455 }
Mikhail Naganov37977152018-07-11 15:54:44 -07005456}
5457
François Gaffiec005e562018-11-06 15:04:49 +01005458bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5459 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005460{
François Gaffiec005e562018-11-06 15:04:49 +01005461 return mEngine->getProductStrategyForAttributes(lAttr) ==
5462 mEngine->getProductStrategyForAttributes(rAttr);
5463}
5464
Francois Gaffie5bd3d2d2020-05-06 18:37:04 +02005465void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
5466{
5467 for (size_t i = 0; i < mAudioSources.size(); i++) {
5468 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5469 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie06e324a2020-10-14 18:02:07 +02005470 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
5471 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffie5bd3d2d2020-05-06 18:37:04 +02005472 connectAudioSource(sourceDesc);
5473 }
5474 }
5475}
5476
5477void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
5478{
5479 for (size_t i = 0; i < mAudioSources.size(); i++) {
5480 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5481 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
5482 && sourceDesc->swOutput().promote()->mIoHandle == output) {
5483 disconnectAudioSource(sourceDesc);
5484 }
5485 }
5486}
5487
François Gaffiec005e562018-11-06 15:04:49 +01005488void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5489{
5490 auto psId = mEngine->getProductStrategyForAttributes(attr);
5491
5492 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5493 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07005494
François Gaffie11d30102018-11-02 16:09:09 +01005495 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5496 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005497
Eric Laurentc209fe42020-06-05 18:11:23 -07005498 uint32_t maxLatency = 0;
5499 bool invalidate = false;
5500 // take into account dynamic audio policies related changes: if a client is now associated
5501 // to a different policy mix than at creation time, invalidate corresponding stream
5502 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5503 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5504 if (desc->isDuplicated()) {
5505 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005506 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005507 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5508 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5509 continue;
5510 }
5511 sp<AudioPolicyMix> primaryMix;
5512 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5513 client->flags(), primaryMix, nullptr);
5514 if (status != OK) {
5515 continue;
5516 }
5517 if (client->getPrimaryMix() != primaryMix) {
5518 invalidate = true;
5519 if (desc->isStrategyActive(psId)) {
5520 maxLatency = desc->latency();
5521 }
5522 break;
5523 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005524 }
5525 }
5526
Eric Laurentc209fe42020-06-05 18:11:23 -07005527 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005528 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5529 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005530 for (audio_io_handle_t srcOut : srcOutputs) {
5531 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005532 if (desc == nullptr) continue;
5533
5534 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005535 maxLatency = desc->latency();
5536 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005537
5538 if (invalidate) continue;
5539
5540 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005541 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005542 // a client on a non direct outputs has necessarily a linear PCM format
5543 // so we can call selectOutput() safely
5544 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5545 client->flags(),
5546 client->config().format,
5547 client->config().channel_mask,
5548 client->config().sample_rate);
5549 if (newOutput != srcOut) {
5550 invalidate = true;
5551 break;
5552 }
5553 } else {
5554 sp<IOProfile> profile = getProfileForOutput(newDevices,
5555 client->config().sample_rate,
5556 client->config().format,
5557 client->config().channel_mask,
5558 client->flags(),
5559 true /* directOnly */);
5560 if (profile != desc->mProfile) {
5561 invalidate = true;
5562 break;
5563 }
5564 }
5565 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005566 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005567
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005568 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005569 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005570 std::to_string(srcOutputs[0]).c_str(),
5571 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005572 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005573 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005574 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005575 if (desc == nullptr) continue;
5576
5577 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005578 setStrategyMute(psId, true, desc);
5579 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005580 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005581 }
François Gaffiec005e562018-11-06 15:04:49 +01005582 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie06e324a2020-10-14 18:02:07 +02005583 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005584 connectAudioSource(source);
5585 }
Eric Laurente552edb2014-03-10 17:42:56 -07005586 }
5587
François Gaffiec005e562018-11-06 15:04:49 +01005588 // Move effects associated to this stream from previous output to new output
5589 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005590 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005591 }
François Gaffiec005e562018-11-06 15:04:49 +01005592 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005593 if (invalidate) {
5594 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5595 mpClientInterface->invalidateStream(stream);
5596 }
Eric Laurente552edb2014-03-10 17:42:56 -07005597 }
5598 }
5599}
5600
Eric Laurente0720872014-03-11 09:30:41 -07005601void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005602{
François Gaffiec005e562018-11-06 15:04:49 +01005603 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5604 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5605 checkOutputForAttributes(attributes);
Francois Gaffie5bd3d2d2020-05-06 18:37:04 +02005606 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01005607 }
Eric Laurente552edb2014-03-10 17:42:56 -07005608}
5609
Kevin Rocard153f92d2018-12-18 18:33:28 -08005610void AudioPolicyManager::checkSecondaryOutputs() {
5611 std::set<audio_stream_type_t> streamsToInvalidate;
5612 for (size_t i = 0; i < mOutputs.size(); i++) {
5613 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5614 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005615 sp<AudioPolicyMix> primaryMix;
5616 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07005617 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07005618 client->flags(), primaryMix, &secondaryMixes);
5619 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5620 for (auto &secondaryMix : secondaryMixes) {
5621 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5622 if (outputDesc != nullptr &&
5623 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5624 secondaryDescs.push_back(outputDesc);
5625 }
5626 }
5627
Kevin Rocard94114a22019-04-01 19:38:23 -07005628 if (status != OK ||
5629 !std::equal(client->getSecondaryOutputs().begin(),
Kevin Rocard153f92d2018-12-18 18:33:28 -08005630 client->getSecondaryOutputs().end(),
5631 secondaryDescs.begin(), secondaryDescs.end())) {
5632 streamsToInvalidate.insert(client->stream());
5633 }
5634 }
5635 }
5636 for (audio_stream_type_t stream : streamsToInvalidate) {
5637 ALOGD("%s Invalidate stream %d due to secondary output change", __func__, stream);
5638 mpClientInterface->invalidateStream(stream);
5639 }
5640}
5641
Eric Laurentcca11ce2020-11-25 15:31:27 +01005642bool AudioPolicyManager::isScoRequestedForComm() const {
5643 AudioDeviceTypeAddrVector devices;
5644 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
5645 for (const auto &device : devices) {
5646 if (audio_is_bluetooth_out_sco_device(device.mType)) {
5647 return true;
5648 }
5649 }
5650 return false;
5651}
5652
Eric Laurente0720872014-03-11 09:30:41 -07005653void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005654{
François Gaffie53615e22015-03-19 09:24:12 +01005655 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005656 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005657 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005658 return;
5659 }
5660
Eric Laurent3a4311c2014-03-17 12:00:47 -07005661 bool isScoConnected =
jiabin12dc6b02019-10-01 09:38:30 -07005662 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
5663 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurentcca11ce2020-11-25 15:31:27 +01005664 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07005665
5666 // if suspended, restore A2DP output if:
5667 // ((SCO device is NOT connected) ||
Eric Laurentcca11ce2020-11-25 15:31:27 +01005668 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07005669 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005670 //
Eric Laurentf732e072016-08-03 19:30:28 -07005671 // if not suspended, suspend A2DP output if:
5672 // (SCO device is connected) &&
Eric Laurentcca11ce2020-11-25 15:31:27 +01005673 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07005674 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005675 //
5676 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005677 if (!isScoConnected ||
Eric Laurentcca11ce2020-11-25 15:31:27 +01005678 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07005679 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005680 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005681
5682 mpClientInterface->restoreOutput(a2dpOutput);
5683 mA2dpSuspended = false;
5684 }
5685 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005686 if (isScoConnected &&
Eric Laurentcca11ce2020-11-25 15:31:27 +01005687 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07005688 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005689 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005690
5691 mpClientInterface->suspendOutput(a2dpOutput);
5692 mA2dpSuspended = true;
5693 }
5694 }
5695}
5696
François Gaffie11d30102018-11-02 16:09:09 +01005697DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5698 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005699{
François Gaffie11d30102018-11-02 16:09:09 +01005700 DeviceVector devices;
5701
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005702 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005703 if (index >= 0) {
5704 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005705 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005706 ALOGV("%s device %s forced by patch %d", __func__,
5707 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5708 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005709 }
5710 }
5711
Dean Wheatley514b4312020-06-17 21:45:00 +10005712 // Do not retrieve engine device for outputs through MSD
5713 // TODO: support explicit routing requests by resetting MSD patch to engine device.
5714 if (outputDesc->devices() == getMsdAudioOutDevices()) {
5715 return outputDesc->devices();
5716 }
5717
Eric Laurent97ac8712018-07-27 18:59:02 -07005718 // Honor explicit routing requests only if no client using default routing is active on this
5719 // input: a specific app can not force routing for other apps by setting a preferred device.
5720 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005721 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005722 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005723 if (device != nullptr) {
5724 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07005725 }
5726
François Gaffiea807ef92018-11-05 10:44:33 +01005727 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5728 // of setForceUse / Default Bus device here
5729 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5730 if (device != nullptr) {
5731 return DeviceVector(device);
5732 }
5733
François Gaffiec005e562018-11-06 15:04:49 +01005734 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5735 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5736 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Eric Laurent484e9272018-06-07 17:29:23 -07005737
François Gaffiec005e562018-11-06 15:04:49 +01005738 if ((hasVoiceStream(streams) &&
Henrik Backlund019c1732019-09-30 14:48:38 +02005739 (isInCall() || mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
5740 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0)) ||
Eric Laurentf23a7712019-02-28 17:15:40 -08005741 ((hasStream(streams, AUDIO_STREAM_ALARM) || hasStream(streams, AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
François Gaffiec005e562018-11-06 15:04:49 +01005742 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) ||
5743 outputDesc->isStrategyActive(productStrategy)) {
5744 // Retrieval of devices for voice DL is done on primary output profile, cannot
5745 // check the route (would force modifying configuration file for this profile)
5746 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5747 break;
5748 }
Eric Laurente552edb2014-03-10 17:42:56 -07005749 }
François Gaffiec005e562018-11-06 15:04:49 +01005750 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01005751 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005752}
5753
François Gaffie11d30102018-11-02 16:09:09 +01005754sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5755 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005756{
François Gaffie11d30102018-11-02 16:09:09 +01005757 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005758
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005759 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005760 if (index >= 0) {
5761 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005762 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005763 ALOGV("getNewInputDevice() device %s forced by patch %d",
5764 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5765 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005766 }
5767 }
5768
Eric Laurent97ac8712018-07-27 18:59:02 -07005769 // Honor explicit routing requests only if no client using default routing is active on this
5770 // input: a specific app can not force routing for other apps by setting a preferred device.
5771 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005772 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5773 if (device != nullptr) {
5774 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005775 }
5776
Eric Laurentdc95a252018-04-12 12:46:56 -07005777 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005778 // a null sp<>, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01005779 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5780 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5781 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005782 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005783 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
François Gaffiec005e562018-11-06 15:04:49 +01005784 device = mEngine->getInputDeviceForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005785 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005786
Eric Laurente552edb2014-03-10 17:42:56 -07005787 return device;
5788}
5789
Eric Laurent794fde22016-03-11 09:50:45 -08005790bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5791 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005792 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005793}
5794
Eric Laurente0720872014-03-11 09:30:41 -07005795audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005796 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005797 // getOutputDevicesForStream's behavior for invalid streams.
5798 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5799 // device for music stream), but we want to return the empty set.
5800 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005801 return AUDIO_DEVICE_NONE;
5802 }
François Gaffie11d30102018-11-02 16:09:09 +01005803 DeviceVector activeDevices;
5804 DeviceVector devices;
Mikhail Naganovdc6be0d2020-09-25 23:03:05 +00005805 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
5806 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01005807 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005808 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005809 }
François Gaffiec005e562018-11-06 15:04:49 +01005810 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005811 devices.merge(curDevices);
5812 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005813 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07005814 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01005815 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005816 }
5817 }
Eric Laurente552edb2014-03-10 17:42:56 -07005818 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005819
Eric Laurentb0688d62018-08-14 15:49:18 -07005820 // Favor devices selected on active streams if any to report correct device in case of
5821 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005822 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005823 devices = activeDevices;
5824 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005825 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5826 and doesn't really need to.*/
jiabin12dc6b02019-10-01 09:38:30 -07005827 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01005828 if (!speakerSafeDevices.isEmpty()) {
jiabin12dc6b02019-10-01 09:38:30 -07005829 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01005830 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005831 }
jiabin12dc6b02019-10-01 09:38:30 -07005832 // FIXME: use DeviceTypeSet when Java layer is ready for it.
5833 return deviceTypesToBitMask(devices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005834}
5835
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005836status_t AudioPolicyManager::getDevicesForAttributes(
5837 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
5838 if (devices == nullptr) {
5839 return BAD_VALUE;
5840 }
5841 // check dynamic policies but only for primary descriptors (secondary not used for audible
5842 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07005843 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005844 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07005845 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005846 if (status != OK) {
5847 return status;
5848 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005849 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
5850 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
5851 devices->push_back(device);
5852 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005853 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005854 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5855 for (const auto& device : curDevices) {
5856 devices->push_back(device->getDeviceTypeAddr());
5857 }
5858 return NO_ERROR;
5859}
5860
Eric Laurente0720872014-03-11 09:30:41 -07005861void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005862 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005863 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01005864 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005865 updateDevicesAndOutputs();
5866 break;
5867 default:
5868 break;
5869 }
5870}
5871
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005872uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005873
5874 // skip beacon mute management if a dedicated TTS output is available
5875 if (mTtsOutputAvailable) {
5876 return 0;
5877 }
5878
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005879 switch(event) {
5880 case STARTING_OUTPUT:
5881 mBeaconMuteRefCount++;
5882 break;
5883 case STOPPING_OUTPUT:
5884 if (mBeaconMuteRefCount > 0) {
5885 mBeaconMuteRefCount--;
5886 }
5887 break;
5888 case STARTING_BEACON:
5889 mBeaconPlayingRefCount++;
5890 break;
5891 case STOPPING_BEACON:
5892 if (mBeaconPlayingRefCount > 0) {
5893 mBeaconPlayingRefCount--;
5894 }
5895 break;
5896 }
5897
5898 if (mBeaconMuteRefCount > 0) {
5899 // any playback causes beacon to be muted
5900 return setBeaconMute(true);
5901 } else {
5902 // no other playback: unmute when beacon starts playing, mute when it stops
5903 return setBeaconMute(mBeaconPlayingRefCount == 0);
5904 }
5905}
5906
5907uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5908 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5909 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5910 // keep track of muted state to avoid repeating mute/unmute operations
5911 if (mBeaconMuted != mute) {
5912 // mute/unmute AUDIO_STREAM_TTS on all outputs
5913 ALOGV("\t muting %d", mute);
5914 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01005915 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005916 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005917 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin12dc6b02019-10-01 09:38:30 -07005918 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005919 const uint32_t latency = desc->latency() * 2;
Eric Laurent33897ba2020-07-23 10:57:02 -07005920 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005921 maxLatency = latency;
5922 }
5923 }
5924 mBeaconMuted = mute;
5925 return maxLatency;
5926 }
5927 return 0;
5928}
5929
Eric Laurente0720872014-03-11 09:30:41 -07005930void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005931{
François Gaffiec005e562018-11-06 15:04:49 +01005932 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07005933 mPreviousOutputs = mOutputs;
5934}
5935
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005936uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01005937 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07005938 uint32_t delayMs)
5939{
5940 // mute/unmute strategies using an incompatible device combination
5941 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5942 // if unmuting, unmute only after the specified delay
5943 if (outputDesc->isDuplicated()) {
5944 return 0;
5945 }
5946
5947 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01005948 DeviceVector devices = outputDesc->devices();
5949 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005950
François Gaffiec005e562018-11-06 15:04:49 +01005951 auto productStrategies = mEngine->getOrderedProductStrategies();
5952 for (const auto &productStrategy : productStrategies) {
5953 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
5954 DeviceVector curDevices =
5955 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
5956 curDevices = curDevices.filter(outputDesc->supportedDevices());
5957 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005958 bool doMute = false;
5959
François Gaffiec005e562018-11-06 15:04:49 +01005960 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005961 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005962 outputDesc->setStrategyMutedByDevice(productStrategy, true);
5963 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005964 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005965 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07005966 }
Eric Laurent99401132014-05-07 19:48:15 -07005967 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005968 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005969 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005970 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005971 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005972 continue;
5973 }
François Gaffiec005e562018-11-06 15:04:49 +01005974 ALOGVV("%s() %s (curDevice %s)", __func__,
5975 mute ? "muting" : "unmuting", curDevices.toString().c_str());
5976 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
5977 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07005978 if (mute) {
5979 // FIXME: should not need to double latency if volume could be applied
5980 // immediately by the audioflinger mixer. We must account for the delay
5981 // between now and the next time the audioflinger thread for this output
5982 // will process a buffer (which corresponds to one buffer size,
5983 // usually 1/2 or 1/4 of the latency).
5984 if (muteWaitMs < desc->latency() * 2) {
5985 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005986 }
5987 }
5988 }
5989 }
5990 }
5991 }
5992
Eric Laurent99401132014-05-07 19:48:15 -07005993 // temporary mute output if device selection changes to avoid volume bursts due to
5994 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01005995 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005996 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5997 // temporary mute duration is conservatively set to 4 times the reported latency
5998 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5999 if (muteWaitMs < tempMuteWaitMs) {
6000 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006001 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006002 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6003 // make sure that we do not start the temporary mute period too early in case of
6004 // delayed device change
6005 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6006 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006007 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006008 }
6009 }
6010
Eric Laurente552edb2014-03-10 17:42:56 -07006011 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6012 if (muteWaitMs > delayMs) {
6013 muteWaitMs -= delayMs;
6014 usleep(muteWaitMs * 1000);
6015 return muteWaitMs;
6016 }
6017 return 0;
6018}
6019
François Gaffie11d30102018-11-02 16:09:09 +01006020uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6021 const DeviceVector &devices,
6022 bool force,
6023 int delayMs,
6024 audio_patch_handle_t *patchHandle,
6025 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006026{
François Gaffie11d30102018-11-02 16:09:09 +01006027 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006028 uint32_t muteWaitMs;
6029
6030 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006031 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6032 nullptr /* patchHandle */, requiresMuteCheck);
6033 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6034 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006035 return muteWaitMs;
6036 }
Eric Laurente552edb2014-03-10 17:42:56 -07006037
6038 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006039 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006040 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07006041
François Gaffie11d30102018-11-02 16:09:09 +01006042 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6043
6044 if (!filteredDevices.isEmpty()) {
6045 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006046 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006047
6048 // if the outputs are not materially active, there is no need to mute.
6049 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006050 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006051 } else {
6052 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6053 muteWaitMs = 0;
6054 }
Eric Laurente552edb2014-03-10 17:42:56 -07006055
Eric Laurent79ea9582020-06-11 18:49:24 -07006056 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6057 // output profile or if new device is not supported AND previous device(s) is(are) still
6058 // available (otherwise reset device must be done on the output)
6059 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
6060 !mAvailableOutputDevices.filter(prevDevices).empty()) {
6061 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6062 // restore previous device after evaluating strategy mute state
6063 outputDesc->setDevices(prevDevices);
6064 return muteWaitMs;
6065 }
6066
Eric Laurente552edb2014-03-10 17:42:56 -07006067 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006068 // the requested device is AUDIO_DEVICE_NONE
6069 // OR the requested device is the same as current device
6070 // AND force is not specified
6071 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006072 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006073 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01006074 !force && outputDesc->getPatchHandle() != 0) {
6075 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6076 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07006077 return muteWaitMs;
6078 }
6079
François Gaffie11d30102018-11-02 16:09:09 +01006080 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006081
Eric Laurente552edb2014-03-10 17:42:56 -07006082 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01006083 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006084 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006085 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006086 PatchBuilder patchBuilder;
6087 patchBuilder.addSource(outputDesc);
6088 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6089 for (const auto &filteredDevice : filteredDevices) {
6090 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006091 }
6092
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006093 // Add half reported latency to delayMs when muteWaitMs is null in order
6094 // to avoid disordered sequence of muting volume and changing devices.
6095 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6096 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006097 }
Eric Laurente552edb2014-03-10 17:42:56 -07006098
6099 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006100 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006101
6102 return muteWaitMs;
6103}
6104
Eric Laurentc75307b2015-03-17 15:29:32 -07006105status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006106 int delayMs,
6107 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006108{
Eric Laurent6a94d692014-05-20 11:18:06 -07006109 ssize_t index;
6110 if (patchHandle) {
6111 index = mAudioPatches.indexOfKey(*patchHandle);
6112 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006113 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006114 }
6115 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006116 return INVALID_OPERATION;
6117 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006118 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01006119 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006120 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006121 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffiead447b72019-11-18 15:50:22 +01006122 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006123 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006124 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006125 return status;
6126}
6127
6128status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006129 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006130 bool force,
6131 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006132{
6133 status_t status = NO_ERROR;
6134
Eric Laurent1f2f2232014-06-02 12:01:23 -07006135 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006136 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6137 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006138
François Gaffie11d30102018-11-02 16:09:09 +01006139 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006140 PatchBuilder patchBuilder;
6141 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006142 // AUDIO_SOURCE_HOTWORD is for internal use only:
6143 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006144 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6145 auto result = usecase;
6146 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6147 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6148 }
6149 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006150 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006151 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006152 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006153 }
6154 }
6155 return status;
6156}
6157
Eric Laurent6a94d692014-05-20 11:18:06 -07006158status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6159 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006160{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006161 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006162 ssize_t index;
6163 if (patchHandle) {
6164 index = mAudioPatches.indexOfKey(*patchHandle);
6165 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006166 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006167 }
6168 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006169 return INVALID_OPERATION;
6170 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006171 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01006172 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006173 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006174 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffiead447b72019-11-18 15:50:22 +01006175 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006176 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006177 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006178 return status;
6179}
6180
François Gaffie11d30102018-11-02 16:09:09 +01006181sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006182 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006183 audio_format_t& format,
6184 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006185 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006186{
6187 // Choose an input profile based on the requested capture parameters: select the first available
6188 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006189 //
6190 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6191 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006192
Glenn Kasten730b9262018-03-29 15:01:26 -07006193 sp<IOProfile> firstInexact;
6194 uint32_t updatedSamplingRate = 0;
6195 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6196 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006197 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006198 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006199 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006200 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006201 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006202 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006203 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006204 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006205 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006206 &channelMask /*updatedChannelMask*/,
6207 // FIXME ugly cast
6208 (audio_output_flags_t) flags,
6209 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006210 return profile;
6211 }
François Gaffie11d30102018-11-02 16:09:09 +01006212 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006213 samplingRate,
6214 &updatedSamplingRate,
6215 format,
6216 &updatedFormat,
6217 channelMask,
6218 &updatedChannelMask,
6219 // FIXME ugly cast
6220 (audio_output_flags_t) flags,
6221 false /*exactMatchRequiredForInputFlags*/)) {
6222 firstInexact = profile;
6223 }
6224
Eric Laurente552edb2014-03-10 17:42:56 -07006225 }
6226 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006227 if (firstInexact != nullptr) {
6228 samplingRate = updatedSamplingRate;
6229 format = updatedFormat;
6230 channelMask = updatedChannelMask;
6231 return firstInexact;
6232 }
Eric Laurente552edb2014-03-10 17:42:56 -07006233 return NULL;
6234}
6235
François Gaffieaaac0fd2018-11-22 17:56:39 +01006236float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6237 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006238 int index,
jiabin12dc6b02019-10-01 09:38:30 -07006239 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006240{
jiabin12dc6b02019-10-01 09:38:30 -07006241 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006242
6243 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6244 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6245 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6246 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006247 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6248 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6249 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6250 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi86903e02019-07-11 14:55:16 -07006251 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006252
Jean-Michel Trivi86903e02019-07-11 14:55:16 -07006253 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006254 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6255 mOutputs.isActive(ringVolumeSrc, 0)) {
6256 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin12dc6b02019-10-01 09:38:30 -07006257 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006258 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006259 }
6260
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006261 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006262 if ((volumeSource != callVolumeSrc && (isInCall() ||
6263 mOutputs.isActiveLocally(callVolumeSrc))) &&
6264 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6265 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6266 volumeSource == alarmVolumeSrc ||
6267 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6268 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6269 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi86903e02019-07-11 14:55:16 -07006270 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006271 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin12dc6b02019-10-01 09:38:30 -07006272 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006273 const float maxVoiceVolDb =
jiabin12dc6b02019-10-01 09:38:30 -07006274 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006275 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006276 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6277 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6278 // programmatically muted.
6279 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6280 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6281 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi86903e02019-07-11 14:55:16 -07006282 bool exemptFromCapping =
6283 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6284 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006285 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6286 volumeSource, volumeDb);
6287 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006288 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6289 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6290 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006291 }
6292 }
Eric Laurente552edb2014-03-10 17:42:56 -07006293 // if a headset is connected, apply the following rules to ring tones and notifications
6294 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006295 // - always attenuate notifications volume by 6dB
6296 // - attenuate ring tones volume by 6dB unless music is not playing and
6297 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006298 // - if music is playing, always limit the volume to current music volume,
6299 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin12dc6b02019-10-01 09:38:30 -07006300 if (!Intersection(deviceTypes,
6301 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6302 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurent7a62f292020-08-07 10:51:53 -07006303 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6304 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006305 ((volumeSource == alarmVolumeSrc ||
6306 volumeSource == ringVolumeSrc) ||
6307 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6308 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6309 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6310 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6311 curves.canBeMuted()) {
6312
Eric Laurente552edb2014-03-10 17:42:56 -07006313 // when the phone is ringing we must consider that music could have been paused just before
6314 // by the music application and behave as if music was active if the last music track was
6315 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006316 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006317 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006318 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin12dc6b02019-10-01 09:38:30 -07006319 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006320 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6321 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006322 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin12dc6b02019-10-01 09:38:30 -07006323 float musicVolDb = computeVolume(musicCurves,
6324 musicVolumeSrc,
6325 musicCurves.getVolumeIndex(musicDevice),
6326 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006327 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6328 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6329 if (volumeDb > minVolDb) {
6330 volumeDb = minVolDb;
6331 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006332 }
jiabin12dc6b02019-10-01 09:38:30 -07006333 if (!Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6334 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006335 // on A2DP, also ensure notification volume is not too low compared to media when
6336 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006337 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006338 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin12dc6b02019-10-01 09:38:30 -07006339 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6340 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006341 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6342 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006343 }
6344 }
jiabin12dc6b02019-10-01 09:38:30 -07006345 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006346 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006347 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006348 }
6349 }
6350
François Gaffie43c73442018-11-08 08:21:55 +01006351 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006352}
6353
Eric Laurent3839bc02018-07-10 18:33:34 -07006354int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006355 VolumeSource fromVolumeSource,
6356 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006357{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006358 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006359 return srcIndex;
6360 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006361 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6362 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006363 float minSrc = (float)srcCurves.getVolumeIndexMin();
6364 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6365 float minDst = (float)dstCurves.getVolumeIndexMin();
6366 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006367
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006368 // preserve mute request or correct range
6369 if (srcIndex < minSrc) {
6370 if (srcIndex == 0) {
6371 return 0;
6372 }
6373 srcIndex = minSrc;
6374 } else if (srcIndex > maxSrc) {
6375 srcIndex = maxSrc;
6376 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006377 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6378}
6379
François Gaffieaaac0fd2018-11-22 17:56:39 +01006380status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6381 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006382 int index,
6383 const sp<AudioOutputDescriptor>& outputDesc,
jiabin12dc6b02019-10-01 09:38:30 -07006384 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006385 int delayMs,
6386 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006387{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006388 // do not change actual attributes volume if the attributes is muted
6389 if (outputDesc->isMuted(volumeSource)) {
6390 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6391 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006392 return NO_ERROR;
6393 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006394 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6395 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
6396 bool isVoiceVolSrc = callVolSrc == volumeSource;
6397 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
6398
Eric Laurentcca11ce2020-11-25 15:31:27 +01006399 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006400 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006401 // if sco and call follow same curves, bypass forceUseForComm
6402 if ((callVolSrc != btScoVolSrc) &&
Eric Laurentcca11ce2020-11-25 15:31:27 +01006403 ((isVoiceVolSrc && isScoRequested) ||
6404 (isBtScoVolSrc && !isScoRequested))) {
6405 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6406 volumeSource, isScoRequested ? " " : "n ot ");
6407 // Do not return an error here as AudioService will always set both voice call
6408 // and bluetooth SCO volumes due to stream aliasing.
6409 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006410 }
jiabin12dc6b02019-10-01 09:38:30 -07006411 if (deviceTypes.empty()) {
6412 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006413 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006414
jiabin12dc6b02019-10-01 09:38:30 -07006415 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6416 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent3ea637c2020-10-12 17:10:23 -07006417 // Force VoIP volume to max for bluetooth SCO device except if muted
6418 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin12dc6b02019-10-01 09:38:30 -07006419 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006420 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006421 }
jiabin12dc6b02019-10-01 09:38:30 -07006422 outputDesc->setVolume(
6423 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006424
François Gaffieaaac0fd2018-11-22 17:56:39 +01006425 if (isVoiceVolSrc || isBtScoVolSrc) {
Eric Laurente552edb2014-03-10 17:42:56 -07006426 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006427 // 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 +01006428 if (isVoiceVolSrc) {
6429 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006430 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006431 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006432 }
Eric Laurent18fba842016-03-31 14:41:26 -07006433 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006434 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6435 mLastVoiceVolume = voiceVolume;
6436 }
6437 }
Eric Laurente552edb2014-03-10 17:42:56 -07006438 return NO_ERROR;
6439}
6440
Eric Laurentc75307b2015-03-17 15:29:32 -07006441void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin12dc6b02019-10-01 09:38:30 -07006442 const DeviceTypeSet& deviceTypes,
6443 int delayMs,
6444 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006445{
Francois Gaffie5992b182020-03-20 14:55:14 +01006446 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006447 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6448 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6449 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin12dc6b02019-10-01 09:38:30 -07006450 curves.getVolumeIndex(deviceTypes),
6451 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006452 }
6453}
6454
François Gaffiec005e562018-11-06 15:04:49 +01006455void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6456 bool on,
6457 const sp<AudioOutputDescriptor>& outputDesc,
6458 int delayMs,
jiabin12dc6b02019-10-01 09:38:30 -07006459 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006460{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006461 std::vector<VolumeSource> sourcesToMute;
6462 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6463 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6464 toString(attributes).c_str(), on, outputDesc->getId());
6465 VolumeSource source = toVolumeSource(attributes);
6466 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
6467 sourcesToMute.push_back(source);
6468 }
Eric Laurente552edb2014-03-10 17:42:56 -07006469 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006470 for (auto source : sourcesToMute) {
jiabin12dc6b02019-10-01 09:38:30 -07006471 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006472 }
6473
Eric Laurente552edb2014-03-10 17:42:56 -07006474}
6475
François Gaffieaaac0fd2018-11-22 17:56:39 +01006476void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6477 bool on,
6478 const sp<AudioOutputDescriptor>& outputDesc,
6479 int delayMs,
jiabin12dc6b02019-10-01 09:38:30 -07006480 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006481{
jiabin12dc6b02019-10-01 09:38:30 -07006482 if (deviceTypes.empty()) {
6483 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006484 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006485 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006486 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006487 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006488 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006489 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6490 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6491 AUDIO_POLICY_FORCE_NONE))) {
jiabin12dc6b02019-10-01 09:38:30 -07006492 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006493 }
6494 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006495 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6496 // ignored
6497 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006498 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006499 if (!outputDesc->isMuted(volumeSource)) {
6500 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006501 return;
6502 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006503 if (outputDesc->decMuteCount(volumeSource) == 0) {
6504 checkAndSetVolume(curves, volumeSource,
jiabin12dc6b02019-10-01 09:38:30 -07006505 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006506 outputDesc,
jiabin12dc6b02019-10-01 09:38:30 -07006507 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006508 delayMs);
6509 }
6510 }
6511}
6512
François Gaffie53615e22015-03-19 09:24:12 +01006513bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6514{
François Gaffiec005e562018-11-06 15:04:49 +01006515 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006516 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6517 return true;
6518 }
6519
6520 // has known usage?
6521 switch (paa->usage) {
6522 case AUDIO_USAGE_UNKNOWN:
6523 case AUDIO_USAGE_MEDIA:
6524 case AUDIO_USAGE_VOICE_COMMUNICATION:
6525 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6526 case AUDIO_USAGE_ALARM:
6527 case AUDIO_USAGE_NOTIFICATION:
6528 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6529 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6530 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6531 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6532 case AUDIO_USAGE_NOTIFICATION_EVENT:
6533 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6534 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6535 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6536 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006537 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006538 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006539 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006540 case AUDIO_USAGE_EMERGENCY:
6541 case AUDIO_USAGE_SAFETY:
6542 case AUDIO_USAGE_VEHICLE_STATUS:
6543 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006544 break;
6545 default:
6546 return false;
6547 }
6548 return true;
6549}
6550
François Gaffie2110e042015-03-24 08:41:51 +01006551audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6552{
6553 return mEngine->getForceUse(usage);
6554}
6555
6556bool AudioPolicyManager::isInCall()
6557{
6558 return isStateInCall(mEngine->getPhoneState());
6559}
6560
6561bool AudioPolicyManager::isStateInCall(int state)
6562{
6563 return is_state_in_call(state);
6564}
6565
Eric Laurent74b71512019-11-06 17:21:57 -08006566bool AudioPolicyManager::isCallAudioAccessible()
6567{
6568 audio_mode_t mode = mEngine->getPhoneState();
6569 return (mode == AUDIO_MODE_IN_CALL)
6570 || (mode == AUDIO_MODE_IN_COMMUNICATION)
6571 || (mode == AUDIO_MODE_CALL_SCREEN);
6572}
6573
Eric Laurentd60560a2015-04-10 11:31:20 -07006574void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6575{
6576 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006577 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffied2c073b2020-09-29 16:05:07 +02006578 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie06e324a2020-10-14 18:02:07 +02006579 sourceDesc->sinkDevice()->equals(deviceDesc))
6580 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffied2c073b2020-09-29 16:05:07 +02006581 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006582 }
6583 }
6584
6585 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6586 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6587 bool release = false;
6588 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6589 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6590 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6591 source->ext.device.type == deviceDesc->type()) {
6592 release = true;
6593 }
6594 }
Francois Gaffied2c073b2020-09-29 16:05:07 +02006595 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07006596 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6597 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6598 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffied2c073b2020-09-29 16:05:07 +02006599 sink->ext.device.type == deviceDesc->type() &&
6600 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
6601 || strncmp(sink->ext.device.address, address,
6602 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006603 release = true;
6604 }
6605 }
6606 if (release) {
François Gaffiead447b72019-11-18 15:50:22 +01006607 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6608 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006609 }
6610 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006611
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006612 mInputs.clearSessionRoutesForDevice(deviceDesc);
6613
Francois Gaffie716e1432019-01-14 16:58:59 +01006614 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006615}
6616
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006617void AudioPolicyManager::modifySurroundFormats(
6618 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006619 std::unordered_set<audio_format_t> enforcedSurround(
6620 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006621 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6622 for (const auto& pair : mConfig.getSurroundFormats()) {
6623 allSurround.insert(pair.first);
6624 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6625 }
Phil Burk09bc4612016-02-24 15:58:15 -08006626
6627 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6628 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07006629 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006630 // This is the resulting set of formats depending on the surround mode:
6631 // 'all surround' = allSurround
6632 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
6633 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
6634 // 'manual surround' = mManualSurroundFormats
6635 // AUTO: formats v 'enforced surround'
6636 // ALWAYS: formats v 'all surround' v 'enforced surround'
6637 // NEVER: formats ^ 'non-surround'
6638 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08006639
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006640 std::unordered_set<audio_format_t> formatSet;
6641 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
6642 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006643 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006644 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006645 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006646 formatSet.insert(*formatIter);
6647 }
6648 }
6649 } else {
6650 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6651 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006652 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006653
jiabin81772902018-04-02 17:52:27 -07006654 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006655 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006656 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6657 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6658 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08006659 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006660 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6661 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6662 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07006663 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006664 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08006665 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006666 for (const auto& format : formatSet) {
jiabin4562b3b2019-07-29 10:13:34 -07006667 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006668 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006669}
6670
jiabin4562b3b2019-07-29 10:13:34 -07006671void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
6672 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07006673 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6674 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6675
6676 // If NEVER, then remove support for channelMasks > stereo.
6677 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin4562b3b2019-07-29 10:13:34 -07006678 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
6679 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006680 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6681 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin4562b3b2019-07-29 10:13:34 -07006682 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07006683 } else {
jiabin4562b3b2019-07-29 10:13:34 -07006684 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006685 }
6686 }
jiabin81772902018-04-02 17:52:27 -07006687 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6688 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6689 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006690 bool supports5dot1 = false;
6691 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006692 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006693 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6694 supports5dot1 = true;
6695 break;
6696 }
6697 }
6698 // If not then add 5.1 support.
6699 if (!supports5dot1) {
jiabin4562b3b2019-07-29 10:13:34 -07006700 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006701 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006702 }
Phil Burk09bc4612016-02-24 15:58:15 -08006703 }
6704}
6705
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006706void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006707 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006708 AudioProfileVector &profiles)
6709{
6710 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006711 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006712
François Gaffie112b0af2015-11-19 16:13:25 +01006713 // Format MUST be checked first to update the list of AudioProfile
6714 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006715 reply = mpClientInterface->getParameters(
6716 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006717 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006718 AudioParameter repliedParameters(reply);
6719 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006720 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006721 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6722 return;
6723 }
Phil Burk09bc4612016-02-24 15:58:15 -08006724 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006725 if (device == AUDIO_DEVICE_OUT_HDMI
6726 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006727 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006728 }
jiabinb9733bc2019-09-10 14:27:34 -07006729 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006730 }
François Gaffie112b0af2015-11-19 16:13:25 +01006731
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006732 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin4562b3b2019-07-29 10:13:34 -07006733 ChannelMaskSet channelMasks;
6734 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006735 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006736 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006737
6738 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006739 reply = mpClientInterface->getParameters(
6740 ioHandle,
6741 requestedParameters.toString() + ";" +
6742 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006743 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006744 AudioParameter repliedParameters(reply);
6745 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006746 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006747 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006748 }
6749 }
6750 if (profiles.hasDynamicChannelsFor(format)) {
6751 reply = mpClientInterface->getParameters(ioHandle,
6752 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006753 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006754 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006755 AudioParameter repliedParameters(reply);
6756 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006757 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006758 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006759 if (device == AUDIO_DEVICE_OUT_HDMI
6760 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006761 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006762 }
François Gaffie112b0af2015-11-19 16:13:25 +01006763 }
6764 }
jiabinb9733bc2019-09-10 14:27:34 -07006765 addDynamicAudioProfileAndSort(
6766 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006767 }
6768}
Eric Laurentd60560a2015-04-10 11:31:20 -07006769
Mikhail Naganovdc769682018-05-04 15:34:08 -07006770status_t AudioPolicyManager::installPatch(const char *caller,
6771 audio_patch_handle_t *patchHandle,
6772 AudioIODescriptorInterface *ioDescriptor,
6773 const struct audio_patch *patch,
6774 int delayMs)
6775{
6776 ssize_t index = mAudioPatches.indexOfKey(
6777 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6778 *patchHandle : ioDescriptor->getPatchHandle());
6779 sp<AudioPatch> patchDesc;
6780 status_t status = installPatch(
6781 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6782 if (status == NO_ERROR) {
François Gaffiead447b72019-11-18 15:50:22 +01006783 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07006784 }
6785 return status;
6786}
6787
6788status_t AudioPolicyManager::installPatch(const char *caller,
6789 ssize_t index,
6790 audio_patch_handle_t *patchHandle,
6791 const struct audio_patch *patch,
6792 int delayMs,
6793 uid_t uid,
6794 sp<AudioPatch> *patchDescPtr)
6795{
6796 sp<AudioPatch> patchDesc;
6797 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6798 if (index >= 0) {
6799 patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01006800 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006801 }
6802
6803 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6804 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6805 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6806 if (status == NO_ERROR) {
6807 if (index < 0) {
6808 patchDesc = new AudioPatch(patch, uid);
François Gaffiead447b72019-11-18 15:50:22 +01006809 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006810 } else {
6811 patchDesc->mPatch = *patch;
6812 }
François Gaffiead447b72019-11-18 15:50:22 +01006813 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006814 if (patchHandle) {
François Gaffiead447b72019-11-18 15:50:22 +01006815 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006816 }
6817 nextAudioPortGeneration();
6818 mpClientInterface->onAudioPatchListUpdate();
6819 }
6820 if (patchDescPtr) *patchDescPtr = patchDesc;
6821 return status;
6822}
6823
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006824} // namespace android