blob: 6b664ddcfade9da54502ec66421cc28baf64dde7 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Eric Laurent16c66dd2019-05-01 17:54:10 -070032#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070033#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070034#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080035#include <set>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080036#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110037#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070038
39#include <Serializer.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070040#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070041#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070042#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070043#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070044#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070045#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070046#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070047#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070048#include <utils/Log.h>
49
Eric Laurentd4692962014-05-05 18:13:44 -070050#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010051#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070052
Eric Laurent3b73df72014-03-11 09:06:29 -070053namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurentdc462862016-07-19 12:29:53 -070055//FIXME: workaround for truncated touch sounds
56// to be removed when the problem is handled by system UI
57#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070058
59// Largest difference in dB on earpiece in call between the voice volume and another
60// media / notification / system volume.
61constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
62
Mikhail Naganov15be9d22017-11-08 14:18:13 +110063// Compressed formats for MSD module, ordered from most preferred to least preferred.
Dean Wheatley8bee85a2021-02-10 16:02:23 +110064static const std::vector<audio_format_t> msdCompressedFormatsOrder = {{
65 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Mikhail Naganov15be9d22017-11-08 14:18:13 +110066 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
67// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
Dean Wheatley8bee85a2021-02-10 16:02:23 +110068static const std::vector<audio_channel_mask_t> msdSurroundChannelMasksOrder = {{
Mikhail Naganov15be9d22017-11-08 14:18:13 +110069 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
70 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
71 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
72
jiabin06e4bab2019-07-29 10:13:34 -070073template <typename T>
74bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
75{
76 if (left.size() != right.size()) {
77 return false;
78 }
79 for (size_t index = 0; index < right.size(); index++) {
80 if (left[index] != right[index]) {
81 return false;
82 }
83 }
84 return true;
85}
86
87template <typename T>
88bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
89{
90 return !(left == right);
91}
92
Eric Laurente552edb2014-03-10 17:42:56 -070093// ----------------------------------------------------------------------------
94// AudioPolicyInterface implementation
95// ----------------------------------------------------------------------------
96
Eric Laurente0720872014-03-11 09:30:41 -070097status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080098 audio_policy_dev_state_t state,
99 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800100 const char *device_name,
101 audio_format_t encodedFormat)
Eric Laurente552edb2014-03-10 17:42:56 -0700102{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800103 status_t status = setDeviceConnectionStateInt(device, state, device_address,
104 device_name, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800105 nextAudioPortGeneration();
106 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800107}
108
François Gaffie11d30102018-11-02 16:09:09 +0100109void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
110 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200111{
jiabince9f20e2019-09-12 16:29:15 -0700112 AudioParameter param(String8(device->address().c_str()));
François Gaffie44481e72016-04-20 07:49:57 +0200113 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganovf23fcf62019-07-08 15:28:43 -0700114 AudioParameter::keyDeviceConnect : AudioParameter::keyDeviceDisconnect);
François Gaffie11d30102018-11-02 16:09:09 +0100115 param.addInt(key, device->type());
François Gaffie44481e72016-04-20 07:49:57 +0200116 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
117}
118
François Gaffie11d30102018-11-02 16:09:09 +0100119status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800120 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800121 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800122 const char *device_name,
123 audio_format_t encodedFormat)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800124{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800125 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s format 0x%X",
126 deviceType, state, device_address, device_name, encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700127
128 // connect/disconnect only 1 device at a time
François Gaffie11d30102018-11-02 16:09:09 +0100129 if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -0700130
François Gaffie11d30102018-11-02 16:09:09 +0100131 sp<DeviceDescriptor> device =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800132 mHwModules.getDeviceDescriptor(deviceType, device_address, device_name, encodedFormat,
Francois Gaffie716e1432019-01-14 16:58:59 +0100133 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700134 return device ? setDeviceConnectionStateInt(device, state) : INVALID_OPERATION;
135}
Paul McLeane743a472015-01-28 11:07:31 -0800136
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700137status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
138 audio_policy_dev_state_t state)
139{
Eric Laurente552edb2014-03-10 17:42:56 -0700140 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700141 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700142 SortedVector <audio_io_handle_t> outputs;
143
François Gaffie11d30102018-11-02 16:09:09 +0100144 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700145
Eric Laurente552edb2014-03-10 17:42:56 -0700146 // save a copy of the opened output descriptors before any output is opened or closed
147 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
148 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700149 switch (state)
150 {
151 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800152 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700153 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100154 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700155 return INVALID_OPERATION;
156 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800157 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700158 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700159
Eric Laurente552edb2014-03-10 17:42:56 -0700160 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200161 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700162 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700163 }
164
François Gaffie44481e72016-04-20 07:49:57 +0200165 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
166 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100167 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200168
François Gaffie11d30102018-11-02 16:09:09 +0100169 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
170 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200171
Francois Gaffie716e1432019-01-14 16:58:59 +0100172 mHwModules.cleanUpForDevice(device);
173
François Gaffie11d30102018-11-02 16:09:09 +0100174 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700175 return INVALID_OPERATION;
176 }
François Gaffie2110e042015-03-24 08:41:51 +0100177
jiabin1c4794b2020-05-05 10:08:05 -0700178 // Populate encapsulation information when a output device is connected.
179 device->setEncapsulationInfoFromHal(mpClientInterface);
180
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700181 // outputs should never be empty here
182 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
183 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100184 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800185
Eric Laurent3ae5f312015-02-03 17:12:08 -0800186 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700187 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700188 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700189 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100190 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700191 return INVALID_OPERATION;
192 }
193
François Gaffie11d30102018-11-02 16:09:09 +0100194 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700195
Paul McLeane743a472015-01-28 11:07:31 -0800196 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100197 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700198
Eric Laurente552edb2014-03-10 17:42:56 -0700199 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100200 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700201
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100202 mOutputs.clearSessionRoutesForDevice(device);
203
François Gaffie11d30102018-11-02 16:09:09 +0100204 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100205
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800206 // Reset active device codec
207 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
208
Kriti Dangef6be8f2020-11-05 11:58:19 +0100209 // remove device from mReportedFormatsMap cache
210 mReportedFormatsMap.erase(device);
211
Eric Laurente552edb2014-03-10 17:42:56 -0700212 } break;
213
214 default:
François Gaffie11d30102018-11-02 16:09:09 +0100215 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700216 return BAD_VALUE;
217 }
218
Eric Laurent736a1022019-03-27 18:28:46 -0700219 // Propagate device availability to Engine
220 setEngineDeviceConnectionState(device, state);
221
Eric Laurentae970022019-01-29 14:25:04 -0800222 // No need to evaluate playback routing when connecting a remote submix
223 // output device used by a dynamic policy of type recorder as no
224 // playback use case is affected.
225 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700226 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800227 for (audio_io_handle_t output : outputs) {
228 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800229 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
230 if (policyMix != nullptr
231 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700232 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800233 doCheckForDeviceAndOutputChanges = false;
234 break;
235 }
236 }
237 }
238
239 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700240 // outputs must be closed after checkOutputForAllStrategies() is executed
241 if (!outputs.isEmpty()) {
242 for (audio_io_handle_t output : outputs) {
243 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100244 // close unused outputs after device disconnection or direct outputs that have
245 // been opened by checkOutputsForDevice() to query dynamic parameters
Mikhail Naganov37977152018-07-11 15:54:44 -0700246 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
247 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurentae970022019-01-29 14:25:04 -0800248 (desc->mDirectOpenCount == 0))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200249 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700250 closeOutput(output);
251 }
Eric Laurente552edb2014-03-10 17:42:56 -0700252 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700253 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
254 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700255 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700256 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800257 };
258
259 if (doCheckForDeviceAndOutputChanges) {
260 checkForDeviceAndOutputChanges(checkCloseOutputs);
261 } else {
262 checkCloseOutputs();
263 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100264 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700265 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100266 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700267 const DeviceVector activeMediaDevices =
268 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700269 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700270 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530271 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
272 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100273 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700274 // do not force device change on duplicated output because if device is 0, it will
275 // also force a device 0 for the two outputs it is duplicated to which may override
276 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100277 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100278 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700279 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700280 // always force when disconnecting (a non-duplicated device)
281 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100282 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700283 }
jiabinbce0c1d2020-10-05 11:20:18 -0700284 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
285 desc->devices() != activeMediaDevices &&
286 desc->supportsDevicesForPlayback(activeMediaDevices)) {
287 // Reopen the output to query the dynamic profiles when there is not active
288 // clients or all active clients will be rerouted. Otherwise, set the flag
289 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
290 // can be reopened to query dynamic profiles when all clients are inactive.
291 if (areAllActiveTracksRerouted(desc)) {
292 outputsToReopen.push_back(mOutputs.keyAt(i));
293 } else {
294 desc->mPendingReopenToQueryProfiles = true;
295 }
296 }
297 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
298 // Clear the flag that previously set for re-querying profiles.
299 desc->mPendingReopenToQueryProfiles = false;
300 }
301 }
302 for (const auto& output : outputsToReopen) {
303 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
304 closeOutput(output);
305 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700306 }
307
Eric Laurentd60560a2015-04-10 11:31:20 -0700308 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100309 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700310 }
311
Eric Laurent72aa32f2014-05-30 18:51:48 -0700312 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700313 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700314 } // end if is output device
315
Eric Laurente552edb2014-03-10 17:42:56 -0700316 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700317 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100318 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700319 switch (state)
320 {
321 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700322 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700323 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100324 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700325 return INVALID_OPERATION;
326 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700327
328 if (mAvailableInputDevices.add(device) < 0) {
329 return NO_MEMORY;
330 }
331
François Gaffie44481e72016-04-20 07:49:57 +0200332 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
333 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100334 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200335
Eric Laurent0dd51852019-04-19 18:18:58 -0700336 if (checkInputsForDevice(device, state) != NO_ERROR) {
337 mAvailableInputDevices.remove(device);
338
François Gaffie11d30102018-11-02 16:09:09 +0100339 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100340
341 mHwModules.cleanUpForDevice(device);
342
Eric Laurentd4692962014-05-05 18:13:44 -0700343 return INVALID_OPERATION;
344 }
345
Eric Laurentd4692962014-05-05 18:13:44 -0700346 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700347
348 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700349 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700350 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100351 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700352 return INVALID_OPERATION;
353 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700354
François Gaffie11d30102018-11-02 16:09:09 +0100355 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700356
357 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100358 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700359
François Gaffie11d30102018-11-02 16:09:09 +0100360 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700361
362 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100363
364 // remove device from mReportedFormatsMap cache
365 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700366 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700367
368 default:
François Gaffie11d30102018-11-02 16:09:09 +0100369 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700370 return BAD_VALUE;
371 }
372
Eric Laurent736a1022019-03-27 18:28:46 -0700373 // Propagate device availability to Engine
374 setEngineDeviceConnectionState(device, state);
375
Eric Laurent0dd51852019-04-19 18:18:58 -0700376 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700377 // As the input device list can impact the output device selection, update
378 // getDeviceForStrategy() cache
379 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700380
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100381 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200382 // Reconnect Audio Source
383 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
384 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
385 checkAudioSourceForAttributes(attributes);
386 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700387 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100388 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700389 }
390
Eric Laurentb52c1522014-05-20 11:27:36 -0700391 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700392 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700393 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700394
François Gaffie11d30102018-11-02 16:09:09 +0100395 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700396 return BAD_VALUE;
397}
398
Eric Laurent736a1022019-03-27 18:28:46 -0700399void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
400 audio_policy_dev_state_t state) {
401
402 // the Engine does not have to know about remote submix devices used by dynamic audio policies
403 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
404 return;
405 }
406 mEngine->setDeviceConnectionState(device, state);
407}
408
409
Eric Laurente0720872014-03-11 09:30:41 -0700410audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100411 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700412{
Eric Laurent634b7142016-04-20 13:48:02 -0700413 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800414 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
415 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700416 (strlen(device_address) != 0)/*matchAddress*/);
417
418 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100419 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700420 device, device_address);
421 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
422 }
François Gaffie53615e22015-03-19 09:24:12 +0100423
Eric Laurent3a4311c2014-03-17 12:00:47 -0700424 DeviceVector *deviceVector;
425
Eric Laurente552edb2014-03-10 17:42:56 -0700426 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700427 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700428 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700429 deviceVector = &mAvailableInputDevices;
430 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100431 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700432 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700433 }
Eric Laurent634b7142016-04-20 13:48:02 -0700434
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800435 return (deviceVector->getDevice(
436 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700437 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800438}
439
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800440status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
441 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800442 const char *device_name,
443 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800444{
445 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700446 String8 reply;
447 AudioParameter param;
448 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800449
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800450 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
451 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800452
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800453 // connect/disconnect only 1 device at a time
454 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
455
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800456 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700457 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800458 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800459 // Nothing to do: device is not connected
460 return NO_ERROR;
461 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800462 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800463
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700464 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800465 // configure codecs.
466 // Handle two specific cases by sending a set parameter to
467 // configure A2DP codecs. No need to toggle device state.
468 // Case 1: A2DP active device switches from primary to primary
469 // module
470 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200471 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700472 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800473 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
474 if (availablePrimaryOutputDevices().contains(devDesc) &&
475 (module != 0 && module->getHandle() == primaryHandle)) {
476 reply = mpClientInterface->getParameters(
477 AUDIO_IO_HANDLE_NONE,
478 String8(AudioParameter::keyReconfigA2dpSupported));
479 AudioParameter repliedParameters(reply);
480 repliedParameters.getInt(
481 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
482 if (isReconfigA2dpSupported) {
483 const String8 key(AudioParameter::keyReconfigA2dp);
484 param.add(key, String8("true"));
485 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
486 devDesc->setEncodedFormat(encodedFormat);
487 return NO_ERROR;
488 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700489 }
490 }
cnx421bd2dcc42020-07-11 14:58:44 +0800491 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
492 for (size_t i = 0; i < mOutputs.size(); i++) {
493 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
494 // mute media strategies and delay device switch by the largest
495 // This avoid sending the music tail into the earpiece or headset.
496 setStrategyMute(musicStrategy, true, desc);
497 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
498 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
499 nullptr, true /*fromCache*/).types());
500 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800501 // Toggle the device state: UNAVAILABLE -> AVAILABLE
502 // This will force reading again the device configuration
503 status = setDeviceConnectionState(device,
504 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800505 device_address, device_name,
506 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800507 if (status != NO_ERROR) {
508 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
509 status);
510 return status;
511 }
512
513 status = setDeviceConnectionState(device,
514 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800515 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800516 if (status != NO_ERROR) {
517 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
518 status);
519 return status;
520 }
521
522 return NO_ERROR;
523}
524
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800525status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
526 std::vector<audio_format_t> *formats)
527{
528 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800529 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800530 std::unordered_set<audio_format_t> formatSet;
531 sp<HwModule> primaryModule =
532 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700533 if (primaryModule == nullptr) {
534 ALOGE("%s() unable to get primary module", __func__);
535 return NO_INIT;
536 }
jiabin9a3361e2019-10-01 09:38:30 -0700537 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
538 getAudioDeviceOutAllA2dpSet());
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800539 for (const auto& device : declaredDevices) {
540 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800541 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800542 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800543 return status;
544}
545
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100546DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
547{
548 DeviceVector rxSinkdevices{};
549 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
550 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
551 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
552 auto rxSinkDevice = rxSinkdevices.itemAt(0);
553 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
554 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
555 // retrieve Rx Source device descriptor
556 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
557 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
558
559 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
560 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
561 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
562 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
563 return DeviceVector(rxSinkDevice);
564 }
565 }
566 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
567 // the device returned is not necessarily reachable via this output
568 // (filter later by setOutputDevices())
569 return getNewOutputDevices(mPrimaryOutput, fromCache);
570}
571
572status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
573{
574 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
575 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
576 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
577 }
578 return INVALID_OPERATION;
579}
580
581status_t AudioPolicyManager::updateCallRoutingInternal(
582 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700583{
584 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100585 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700586 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700587 if(!hasPrimaryOutput() ||
588 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100589 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700590 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100591 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100592
Francois Gaffie716e1432019-01-14 16:58:59 +0100593 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100594 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100595 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100596
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100597 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100598 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700599
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200600 disconnectTelephonyRxAudioSource();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700601 // release TX patch if any
602 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100603 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700604 mCallTxPatch.clear();
605 }
606
François Gaffie9eb18552018-11-05 10:33:26 +0100607 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700608 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100609 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700610 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100611 // retrieve Rx Source and Tx Sink device descriptors
612 sp<DeviceDescriptor> rxSourceDevice =
613 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
614 String8(),
615 AUDIO_FORMAT_DEFAULT);
616 sp<DeviceDescriptor> txSinkDevice =
617 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
618 String8(),
619 AUDIO_FORMAT_DEFAULT);
620
621 // RX and TX Telephony device are declared by Primary Audio HAL
622 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
623 (telephonyRxModule->getHalVersionMajor() >= 3)) {
624 if (rxSourceDevice == 0 || txSinkDevice == 0) {
625 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100626 ALOGE("%s() no telephony Tx and/or RX device", __func__);
627 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100628 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100629 // createAudioPatchInternal now supports both HW / SW bridging
630 createRxPatch = true;
631 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100632 } else {
633 // If the RX device is on the primary HW module, then use legacy routing method for
634 // voice calls via setOutputDevice() on primary output.
635 // Otherwise, create two audio patches for TX and RX path.
636 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
637 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700638 // If the TX device is also on the primary HW module, setOutputDevice() will take care
639 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100640 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
641 (txSinkDevice != 0);
642 }
643 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
644 // Otherwise, create two audio patches for TX and RX path.
645 if (!createRxPatch) {
646 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700647 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200648 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800649 // If the TX device is on the primary HW module but RX device is
650 // on other HW module, SinkMetaData of telephony input should handle it
651 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700652 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700653 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100654 // terminate active capture if on the same HW module as the call TX source device
655 // FIXME: would be better to refine to only inputs whose profile connects to the
656 // call TX device but this information is not in the audio patch and logic here must be
657 // symmetric to the one in startInput()
658 for (const auto& activeDesc : mInputs.getActiveInputs()) {
659 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
660 closeActiveClients(activeDesc);
661 }
662 }
François Gaffie9eb18552018-11-05 10:33:26 +0100663 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800664 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100665 if (waitMs != nullptr) {
666 *waitMs = muteWaitMs;
667 }
668 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800669}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700670
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800671sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100672 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700673 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700674
François Gaffie11d30102018-11-02 16:09:09 +0100675 if (device == nullptr) {
676 return nullptr;
677 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100678
679 // @TODO: still ignoring the address, or not dealing platform with multiple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800680 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100681 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800682 addSource(mAvailableInputDevices.getDevice(
683 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800684 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100685 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800686 addSink(mAvailableOutputDevices.getDevice(
687 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800688 }
689
François Gaffieafd4cea2019-11-18 15:50:22 +0100690 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
691 status_t status =
692 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
693 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
694 if (status != NO_ERROR || index < 0) {
695 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
696 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800697 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100698 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800699}
700
Mikhail Naganov100f0122018-11-29 11:22:16 -0800701bool AudioPolicyManager::isDeviceOfModule(
702 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
703 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
704 if (module != 0) {
705 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
706 .indexOf(devDesc) != NAME_NOT_FOUND
707 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
708 .indexOf(devDesc) != NAME_NOT_FOUND;
709 }
710 return false;
711}
712
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200713void AudioPolicyManager::connectTelephonyRxAudioSource()
714{
715 disconnectTelephonyRxAudioSource();
716 const struct audio_port_config source = {
717 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
718 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
719 };
720 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
721 status_t status = startAudioSource(&source, &aa, &mCallRxSourceClientPort, 0/*uid*/);
722 ALOGE_IF(status != NO_ERROR, "%s failed to start Telephony Rx AudioSource", __func__);
723}
724
725void AudioPolicyManager::disconnectTelephonyRxAudioSource()
726{
727 stopAudioSource(mCallRxSourceClientPort);
728 mCallRxSourceClientPort = AUDIO_PORT_HANDLE_NONE;
729}
730
Eric Laurente0720872014-03-11 09:30:41 -0700731void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700732{
733 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100734 // store previous phone state for management of sonification strategy below
735 int oldState = mEngine->getPhoneState();
736
737 if (mEngine->setPhoneState(state) != NO_ERROR) {
738 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700739 return;
740 }
François Gaffie2110e042015-03-24 08:41:51 +0100741 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700742 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700743 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700744 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800745 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700746 }
747
François Gaffie2110e042015-03-24 08:41:51 +0100748 /**
749 * Switching to or from incall state or switching between telephony and VoIP lead to force
750 * routing command.
751 */
Eric Laurent74b71512019-11-06 17:21:57 -0800752 bool force = ((isStateInCall(oldState) != isStateInCall(state))
753 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700754
755 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700756 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700757
Eric Laurente552edb2014-03-10 17:42:56 -0700758 int delayMs = 0;
759 if (isStateInCall(state)) {
760 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100761 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
762 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700763 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700764 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700765 // mute media and sonification strategies and delay device switch by the largest
766 // latency of any output where either strategy is active.
767 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100768 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
769 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
770 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700771 (delayMs < (int)desc->latency()*2)) {
772 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700773 }
François Gaffiec005e562018-11-06 15:04:49 +0100774 setStrategyMute(musicStrategy, true, desc);
775 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
776 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
777 nullptr, true /*fromCache*/).types());
778 setStrategyMute(sonificationStrategy, true, desc);
779 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
780 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
781 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700782 }
783 }
784
Eric Laurent87ffa392015-05-22 10:32:38 -0700785 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700786 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100787 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700788 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100789 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
790 // force routing command to audio hardware when ending call
791 // even if no device change is needed
792 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
793 rxDevices = mPrimaryOutput->devices();
794 }
795 if (oldState == AUDIO_MODE_IN_CALL) {
796 disconnectTelephonyRxAudioSource();
797 if (mCallTxPatch != 0) {
798 releaseAudioPatchInternal(mCallTxPatch->getHandle());
799 mCallTxPatch.clear();
800 }
801 }
François Gaffie11d30102018-11-02 16:09:09 +0100802 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700803 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700804 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700805
806 // reevaluate routing on all outputs in case tracks have been started during the call
807 for (size_t i = 0; i < mOutputs.size(); i++) {
808 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100809 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700810 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100811 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700812 }
813 }
814
Eric Laurente552edb2014-03-10 17:42:56 -0700815 if (isStateInCall(state)) {
816 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700817 // force reevaluating accessibility routing when call starts
818 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700819 }
820
821 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100822 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
823 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700824}
825
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700826audio_mode_t AudioPolicyManager::getPhoneState() {
827 return mEngine->getPhoneState();
828}
829
Eric Laurente0720872014-03-11 09:30:41 -0700830void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100831 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700832{
François Gaffie2110e042015-03-24 08:41:51 +0100833 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700834 if (config == mEngine->getForceUse(usage)) {
835 return;
836 }
Eric Laurente552edb2014-03-10 17:42:56 -0700837
François Gaffie2110e042015-03-24 08:41:51 +0100838 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
839 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
840 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700841 }
François Gaffie2110e042015-03-24 08:41:51 +0100842 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
843 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
844 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700845
846 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700847 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800848
Eric Laurent22fcda22019-05-17 16:28:47 -0700849 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
850 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
851 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
852 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
853 }
854
Eric Laurentdc462862016-07-19 12:29:53 -0700855 //FIXME: workaround for truncated touch sounds
856 // to be removed when the problem is handled by system UI
857 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700858 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
859 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
860 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700861
862 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100863 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700864}
865
Eric Laurente0720872014-03-11 09:30:41 -0700866void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700867{
868 ALOGV("setSystemProperty() property %s, value %s", property, value);
869}
870
Michael Chana94fbb22018-04-24 14:31:19 +1000871// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
872// search to profiles for direct outputs.
873sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100874 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000875 uint32_t samplingRate,
876 audio_format_t format,
877 audio_channel_mask_t channelMask,
878 audio_output_flags_t flags,
879 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700880{
Michael Chana94fbb22018-04-24 14:31:19 +1000881 if (directOnly) {
882 // only retain flags that will drive the direct output profile selection
883 // if explicitly requested
884 static const uint32_t kRelevantFlags =
885 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lataba810b82019-07-03 11:15:33 -0700886 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000887 flags =
888 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
889 }
Eric Laurent861a6282015-05-18 15:40:16 -0700890
891 sp<IOProfile> profile;
892
Mikhail Naganovd4120142017-12-06 15:49:22 -0800893 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800894 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100895 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700896 samplingRate, NULL /*updatedSamplingRate*/,
897 format, NULL /*updatedFormat*/,
898 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700899 flags)) {
900 continue;
901 }
902 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100903 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700904 continue;
905 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800906 // reject profiles if connected device does not support codec
jiabin9a3361e2019-10-01 09:38:30 -0700907 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800908 continue;
909 }
Michael Chana94fbb22018-04-24 14:31:19 +1000910 if (!directOnly) return curProfile;
911 // when searching for direct outputs, if several profiles are compatible, give priority
912 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100913 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700914 continue;
915 }
916 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100917 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700918 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700919 }
Eric Laurente552edb2014-03-10 17:42:56 -0700920 }
921 }
Eric Laurent861a6282015-05-18 15:40:16 -0700922 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700923}
924
Eric Laurentf4e63452017-11-06 19:31:46 +0000925audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700926{
François Gaffiec005e562018-11-06 15:04:49 +0100927 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800928
929 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
930 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
931 // format, flags, etc. This may result in some discrepancy for functions that utilize
932 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
933 // and AudioSystem::getOutputSamplingRate().
934
François Gaffie11d30102018-11-02 16:09:09 +0100935 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700936 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700937
François Gaffie11d30102018-11-02 16:09:09 +0100938 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
939 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000940 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700941}
942
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700943status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
944 const audio_attributes_t *srcAttr,
945 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700946{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700947 if (srcAttr != NULL) {
948 if (!isValidAttributes(srcAttr)) {
949 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
950 __func__,
951 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
952 srcAttr->tags);
953 return BAD_VALUE;
954 }
955 *dstAttr = *srcAttr;
956 } else {
957 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
958 ALOGE("%s: invalid stream type", __func__);
959 return BAD_VALUE;
960 }
François Gaffiec005e562018-11-06 15:04:49 +0100961 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700962 }
Eric Laurent22fcda22019-05-17 16:28:47 -0700963
964 // Only honor audibility enforced when required. The client will be
965 // forced to reconnect if the forced usage changes.
966 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700967 dstAttr->flags = static_cast<audio_flags_mask_t>(
968 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -0700969 }
970
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700971 return NO_ERROR;
972}
973
Kevin Rocard153f92d2018-12-18 18:33:28 -0800974status_t AudioPolicyManager::getOutputForAttrInt(
975 audio_attributes_t *resultAttr,
976 audio_io_handle_t *output,
977 audio_session_t session,
978 const audio_attributes_t *attr,
979 audio_stream_type_t *stream,
980 uid_t uid,
981 const audio_config_t *config,
982 audio_output_flags_t *flags,
983 audio_port_handle_t *selectedDeviceId,
984 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -0700985 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -0800986 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700987{
François Gaffiec005e562018-11-06 15:04:49 +0100988 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +0100989 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100990 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +0100991 const sp<DeviceDescriptor> requestedDevice =
992 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
993
Eric Laurent8a1095a2019-11-08 14:44:16 -0800994 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700995 status_t status = getAudioAttributes(resultAttr, attr, *stream);
996 if (status != NO_ERROR) {
997 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700998 }
Kevin Rocardb99cc752019-03-21 20:52:24 -0700999 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001000 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001001 }
François Gaffiec005e562018-11-06 15:04:49 +01001002 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001003
François Gaffiec005e562018-11-06 15:04:49 +01001004 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1005 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001006
Kevin Rocard153f92d2018-12-18 18:33:28 -08001007 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1008 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1009 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001010 sp<AudioPolicyMix> primaryMix;
1011 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001012 if (status != OK) {
1013 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001014 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001015
Kevin Rocard153f92d2018-12-18 18:33:28 -08001016 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001017 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001018
1019 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -07001020 if ((usePrimaryOutputFromPolicyMixes
1021 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -08001022 && !audio_is_linear_pcm(config->format)) {
1023 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001024 return BAD_VALUE;
1025 }
1026 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001027 sp<DeviceDescriptor> deviceDesc =
1028 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1029 primaryMix->mDeviceAddress,
1030 AUDIO_FORMAT_DEFAULT);
1031 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001032 if (deviceDesc != nullptr
1033 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001034 audio_io_handle_t newOutput;
1035 status = openDirectOutput(
1036 *stream, session, config,
1037 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1038 DeviceVector(deviceDesc), &newOutput);
1039 if (status != NO_ERROR) {
1040 policyDesc = nullptr;
1041 } else {
1042 policyDesc = mOutputs.valueFor(newOutput);
1043 primaryMix->setOutput(policyDesc);
1044 }
1045 }
1046 if (policyDesc != nullptr) {
1047 policyDesc->mPolicyMix = primaryMix;
1048 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001049 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001050
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001051 ALOGV("getOutputForAttr() returns output %d", *output);
1052 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1053 *outputType = API_OUT_MIX_PLAYBACK;
1054 } else {
1055 *outputType = API_OUTPUT_LEGACY;
1056 }
1057 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001058 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001059 }
François Gaffiec005e562018-11-06 15:04:49 +01001060 // Virtual sources must always be dynamicaly or explicitly routed
1061 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1062 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1063 return BAD_VALUE;
1064 }
1065 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1066 // in order to let the choice of the order to future vendor engine
1067 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001068
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001069 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001070 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001071 }
1072
Nadav Barb2f18162018-07-18 13:01:53 +03001073 // Set incall music only if device was explicitly set, and fallback to the device which is
1074 // chosen by the engine if not.
1075 // FIXME: provide a more generic approach which is not device specific and move this back
1076 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001077 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001078 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001079 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001080 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001081 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001082 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001083 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001084 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001085 }
1086 }
1087
François Gaffiec005e562018-11-06 15:04:49 +01001088 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1089 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1090 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001091
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001092 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001093 if (!msdDevices.isEmpty()) {
1094 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001095 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001096 ALOGV("%s() Using MSD devices %s instead of devices %s",
1097 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001098 } else {
1099 *output = AUDIO_IO_HANDLE_NONE;
1100 }
1101 }
1102 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabine375d412019-02-26 12:54:53 -08001103 *output = getOutputForDevices(outputDevices, session, *stream, config,
Eric Laurent42984412019-05-09 17:57:03 -07001104 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001105 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001106 if (*output == AUDIO_IO_HANDLE_NONE) {
1107 return INVALID_OPERATION;
1108 }
Paul McLeanaa981192015-03-21 09:55:15 -07001109
François Gaffiec005e562018-11-06 15:04:49 +01001110 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001111 for (auto &outputDevice : outputDevices) {
1112 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1113 *selectedDeviceId = outputDevice->getId();
1114 break;
1115 }
1116 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001117
Eric Laurent8a1095a2019-11-08 14:44:16 -08001118 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1119 *outputType = API_OUTPUT_TELEPHONY_TX;
1120 } else {
1121 *outputType = API_OUTPUT_LEGACY;
1122 }
1123
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001124 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1125
1126 return NO_ERROR;
1127}
1128
1129status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1130 audio_io_handle_t *output,
1131 audio_session_t session,
1132 audio_stream_type_t *stream,
1133 uid_t uid,
1134 const audio_config_t *config,
1135 audio_output_flags_t *flags,
1136 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001137 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001138 std::vector<audio_io_handle_t> *secondaryOutputs,
1139 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001140{
1141 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1142 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1143 return INVALID_OPERATION;
1144 }
Francois Gaffie716e1432019-01-14 16:58:59 +01001145 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001146 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001147 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001148 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001149 const sp<DeviceDescriptor> requestedDevice =
1150 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1151
1152 // Prevent from storing invalid requested device id in clients
1153 const audio_port_handle_t sanitizedRequestedPortId =
1154 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1155 *selectedDeviceId = sanitizedRequestedPortId;
1156
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001157 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001158 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001159 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001160 if (status != NO_ERROR) {
1161 return status;
1162 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001163 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001164 if (secondaryOutputs != nullptr) {
1165 for (auto &secondaryMix : secondaryMixes) {
1166 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1167 if (outputDesc != nullptr &&
1168 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1169 secondaryOutputs->push_back(outputDesc->mIoHandle);
1170 weakSecondaryOutputDescs.push_back(outputDesc);
1171 }
1172 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001173 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001174
Eric Laurent8fc147b2018-07-22 19:13:55 -07001175 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001176 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001177 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001178 };
jiabin4ef93452019-09-10 14:29:54 -07001179 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001180
Eric Laurentc209fe42020-06-05 18:11:23 -07001181 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001182 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001183 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001184 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001185 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001186 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001187 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001188 std::move(weakSecondaryOutputDescs),
1189 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001190 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001191
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001192 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1193 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001194
Eric Laurente83b55d2014-11-14 10:06:21 -08001195 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001196}
1197
Eric Laurentc529cf62020-04-17 18:19:10 -07001198status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1199 audio_session_t session,
1200 const audio_config_t *config,
1201 audio_output_flags_t flags,
1202 const DeviceVector &devices,
1203 audio_io_handle_t *output) {
1204
1205 *output = AUDIO_IO_HANDLE_NONE;
1206
1207 // skip direct output selection if the request can obviously be attached to a mixed output
1208 // and not explicitly requested
1209 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1210 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1211 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1212 return NAME_NOT_FOUND;
1213 }
1214
1215 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1216 // This prevents creating an offloaded track and tearing it down immediately after start
1217 // when audioflinger detects there is an active non offloadable effect.
1218 // FIXME: We should check the audio session here but we do not have it in this context.
1219 // This may prevent offloading in rare situations where effects are left active by apps
1220 // in the background.
1221 sp<IOProfile> profile;
1222 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1223 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1224 profile = getProfileForOutput(
1225 devices, config->sample_rate, config->format, config->channel_mask,
1226 flags, true /* directOnly */);
1227 }
1228
1229 if (profile == nullptr) {
1230 return NAME_NOT_FOUND;
1231 }
1232
1233 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1234 for (size_t i = 0; i < mOutputs.size(); i++) {
1235 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1236 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1237 // reuse direct output if currently open by the same client
1238 // and configured with same parameters
1239 if ((config->sample_rate == desc->getSamplingRate()) &&
1240 (config->format == desc->getFormat()) &&
1241 (config->channel_mask == desc->getChannelMask()) &&
1242 (session == desc->mDirectClientSession)) {
1243 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001244 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001245 mOutputs.keyAt(i), session);
1246 *output = mOutputs.keyAt(i);
1247 return NO_ERROR;
1248 }
1249 }
1250 }
1251
1252 if (!profile->canOpenNewIo()) {
1253 return NAME_NOT_FOUND;
1254 }
1255
1256 sp<SwAudioOutputDescriptor> outputDesc =
1257 new SwAudioOutputDescriptor(profile, mpClientInterface);
1258
Michael Chan6fb34492020-12-08 15:44:49 +11001259 // An MSD patch may be using the only output stream that can service this request. Release
1260 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001261 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001262
1263 status_t status = outputDesc->open(config, devices, stream, flags, output);
1264
1265 // only accept an output with the requested parameters
1266 if (status != NO_ERROR ||
1267 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1268 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1269 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1270 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1271 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1272 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1273 config->channel_mask, outputDesc->getChannelMask());
1274 if (*output != AUDIO_IO_HANDLE_NONE) {
1275 outputDesc->close();
1276 }
1277 // fall back to mixer output if possible when the direct output could not be open
1278 if (audio_is_linear_pcm(config->format) &&
1279 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1280 return NAME_NOT_FOUND;
1281 }
1282 *output = AUDIO_IO_HANDLE_NONE;
1283 return BAD_VALUE;
1284 }
1285 outputDesc->mDirectOpenCount = 1;
1286 outputDesc->mDirectClientSession = session;
1287
1288 addOutput(*output, outputDesc);
1289 mPreviousOutputs = mOutputs;
1290 ALOGV("%s returns new direct output %d", __func__, *output);
1291 mpClientInterface->onAudioPortListUpdate();
1292 return NO_ERROR;
1293}
1294
François Gaffie11d30102018-11-02 16:09:09 +01001295audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1296 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001297 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001298 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001299 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001300 audio_output_flags_t *flags,
1301 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001302{
Andy Hungc88b0642018-04-27 15:42:35 -07001303 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001304
jiabine375d412019-02-26 12:54:53 -08001305 // Discard haptic channel mask when forcing muting haptic channels.
1306 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001307 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1308 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001309
Eric Laurente552edb2014-03-10 17:42:56 -07001310 // open a direct output if required by specified parameters
1311 //force direct flag if offload flag is set: offloading implies a direct output stream
1312 // and all common behaviors are driven by checking only the direct flag
1313 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001314 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1315 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001316 }
Nadav Bar766fb022018-01-07 12:18:03 +02001317 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1318 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001319 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001320 // only allow deep buffering for music stream type
1321 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001322 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001323 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001324 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001325 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1326 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001327 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001328 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001329 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001330 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001331 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001332 audio_is_linear_pcm(config->format) &&
1333 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001334 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001335 AUDIO_OUTPUT_FLAG_DIRECT);
1336 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001337 }
Eric Laurente552edb2014-03-10 17:42:56 -07001338
Eric Laurentc529cf62020-04-17 18:19:10 -07001339 audio_config_t directConfig = *config;
1340 directConfig.channel_mask = channelMask;
1341 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1342 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001343 return output;
1344 }
1345
Eric Laurent14cbfca2016-03-17 09:42:16 -07001346 // A request for HW A/V sync cannot fallback to a mixed output because time
1347 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001348 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001349 return AUDIO_IO_HANDLE_NONE;
1350 }
1351
Eric Laurente552edb2014-03-10 17:42:56 -07001352 // ignoring channel mask due to downmix capability in mixer
1353
1354 // open a non direct output
1355
1356 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001357 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001358 // get which output is suitable for the specified stream. The actual
1359 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001360 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001361
Eric Laurent8838a382014-09-08 16:44:28 -07001362 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001363 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001364 output = selectOutput(
1365 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001366 }
François Gaffie11d30102018-11-02 16:09:09 +01001367 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001368 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001369 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001370
Eric Laurente552edb2014-03-10 17:42:56 -07001371 return output;
1372}
1373
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001374sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001375 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1376 mAvailableInputDevices);
1377 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1378}
1379
1380DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1381 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1382 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001383}
1384
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001385const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001386 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001387 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1388 if (msdModule != 0) {
1389 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1390 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1391 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1392 const struct audio_port_config *source = &patch->mPatch.sources[j];
1393 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1394 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001395 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001396 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001397 }
1398 }
1399 }
1400 return msdPatches;
1401}
1402
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001403status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1404 const InputProfileCollection &inputProfiles,
1405 const OutputProfileCollection &outputProfiles,
1406 const sp<DeviceDescriptor> &sourceDevice,
1407 const sp<DeviceDescriptor> &sinkDevice,
1408 AudioProfileVector& sourceProfiles,
1409 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001410 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001411 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001412 return NO_INIT;
1413 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001414 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001415 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001416 return NO_INIT;
1417 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001418 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001419 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1420 inProfile->supportsDevice(sourceDevice)) {
1421 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001422 }
1423 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001424 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001425 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001426 outProfile->supportsDevice(sinkDevice)) {
1427 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001428 }
1429 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001430 return NO_ERROR;
1431}
1432
1433status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1434 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1435 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1436{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001437 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001438 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1439 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1440 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001441 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001442 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1443 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001444 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001445 }
1446 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1447 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1448 sinkConfig->format = bestSinkConfig.format;
1449 // For encoded streams force direct flag to prevent downstream mixing.
1450 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1451 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001452 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1453 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001454 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001455 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1456 // raw and IEC61937 framed streams.
1457 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1458 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1459 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001460 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1461 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1462 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1463 sourceConfig->format = bestSinkConfig.format;
1464 // Copy input stream directly without any processing (e.g. resampling).
1465 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1466 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1467 if (hwAvSync) {
1468 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1469 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1470 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1471 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1472 }
1473 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1474 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1475 sinkConfig->config_mask |= config_mask;
1476 sourceConfig->config_mask |= config_mask;
1477 return NO_ERROR;
1478}
1479
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001480PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1481 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001482{
1483 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001484 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1485 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1486 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1487 if (deviceModule == nullptr) {
1488 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1489 return patchBuilder;
1490 }
1491 const InputProfileCollection inputProfiles = msdIsSource ?
1492 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1493 const OutputProfileCollection outputProfiles = msdIsSource ?
1494 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1495
1496 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1497 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1498 device : getMsdAudioOutDevices().itemAt(0);
1499 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1500
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001501 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1502 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001503 AudioProfileVector sourceProfiles;
1504 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001505 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1506 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001507 for (auto hwAvSync : { true, false }) {
1508 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1509 sourceProfiles, sinkProfiles) != NO_ERROR) {
1510 continue;
1511 }
1512 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1513 &sinkConfig) == NO_ERROR) {
1514 // Found a matching config. Re-create PatchBuilder with this config.
1515 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1516 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001517 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001518 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001519 " supporting PCM format conversion.", __func__);
1520 return patchBuilder;
1521}
1522
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001523status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001524 DeviceVector devices;
1525 if (outputDevices != nullptr && outputDevices->size() > 0) {
1526 devices.add(*outputDevices);
1527 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001528 // Use media strategy for unspecified output device. This should only
1529 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1530 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001531 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001532 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001533 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001534 }
Michael Chan6fb34492020-12-08 15:44:49 +11001535 std::vector<PatchBuilder> patchesToCreate;
1536 for (auto i = 0u; i < devices.size(); ++i) {
1537 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001538 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001539 }
1540 // Retain only the MSD patches associated with outputDevices request.
1541 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001542 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001543 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1544 auto retainedPatch = false;
1545 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1546 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1547 patchesToRemove.removeItemsAt(i);
1548 retainedPatch = true;
1549 break;
1550 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001551 }
Michael Chan6fb34492020-12-08 15:44:49 +11001552 if (retainedPatch) {
1553 it = patchesToCreate.erase(it);
1554 continue;
1555 }
1556 ++it;
1557 }
1558 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1559 return NO_ERROR;
1560 }
1561 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1562 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001563 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001564 }
Michael Chan6fb34492020-12-08 15:44:49 +11001565 status_t status = NO_ERROR;
1566 for (const auto &p : patchesToCreate) {
1567 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1568 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1569 char message[256];
1570 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1571 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1572 currStatus == NO_ERROR ? "Success" : "Error",
1573 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1574 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1575 if (currStatus == NO_ERROR) {
1576 ALOGD("%s", message);
1577 } else {
1578 ALOGE("%s", message);
1579 if (status == NO_ERROR) {
1580 status = currStatus;
1581 }
1582 }
1583 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001584 return status;
1585}
1586
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001587void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1588 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001589 for (size_t i = 0; i < msdPatches.size(); i++) {
1590 const auto& patch = msdPatches[i];
1591 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1592 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1593 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1594 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1595 releaseAudioPatch(patch->getHandle(), mUidCached);
1596 break;
1597 }
1598 }
1599 }
1600}
1601
Eric Laurente0720872014-03-11 09:30:41 -07001602audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001603 audio_output_flags_t flags,
1604 audio_format_t format,
1605 audio_channel_mask_t channelMask,
1606 uint32_t samplingRate,
1607 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001608{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001609 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1610 "%s called with format %#x", __func__, format);
1611
jiabinebb6af42020-06-09 17:31:17 -07001612 // Return the output that haptic-generating attached to when 1) session id is specified,
1613 // 2) haptic-generating effect exists for given session id and 3) the output that
1614 // haptic-generating effect attached to is in given outputs.
1615 if (sessionId != AUDIO_SESSION_NONE) {
1616 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1617 sessionId, FX_IID_HAPTICGENERATOR);
1618 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1619 return hapticGeneratingOutput;
1620 }
1621 }
1622
Eric Laurent16c66dd2019-05-01 17:54:10 -07001623 // Flags disqualifying an output: the match must happen before calling selectOutput()
1624 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1625 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1626
1627 // Flags expressing a functional request: must be honored in priority over
1628 // other criteria
1629 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1630 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1631 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1632 // Flags expressing a performance request: have lower priority than serving
1633 // requested sampling rate or channel mask
1634 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1635 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1636 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1637
1638 const audio_output_flags_t functionalFlags =
1639 (audio_output_flags_t)(flags & kFunctionalFlags);
1640 const audio_output_flags_t performanceFlags =
1641 (audio_output_flags_t)(flags & kPerformanceFlags);
1642
1643 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1644
Eric Laurente552edb2014-03-10 17:42:56 -07001645 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001646 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001647 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001648 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001649 // 2: the output with the highest number of requested functional flags
1650 // 3: the output supporting the exact channel mask
1651 // 4: the output with a higher channel count than requested
1652 // 5: the output with a higher sampling rate than requested
1653 // 6: the output with the highest number of requested performance flags
1654 // 7: the output with the bit depth the closest to the requested one
1655 // 8: the primary output
1656 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001657
Eric Laurent16c66dd2019-05-01 17:54:10 -07001658 // matching criteria values in priority order for best matching output so far
1659 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001660
Eric Laurent16c66dd2019-05-01 17:54:10 -07001661 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1662 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1663 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001664
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001665 for (audio_io_handle_t output : outputs) {
1666 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001667 // matching criteria values in priority order for current output
1668 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001669
Eric Laurent16c66dd2019-05-01 17:54:10 -07001670 if (outputDesc->isDuplicated()) {
1671 continue;
1672 }
1673 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1674 continue;
1675 }
Eric Laurent8838a382014-09-08 16:44:28 -07001676
Eric Laurent16c66dd2019-05-01 17:54:10 -07001677 // If haptic channel is specified, use the haptic output if present.
1678 // When using haptic output, same audio format and sample rate are required.
1679 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001680 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001681 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1682 continue;
1683 }
1684 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001685 && format == outputDesc->getFormat()
1686 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001687 currentMatchCriteria[0] = outputHapticChannelCount;
1688 }
1689
1690 // functional flags match
1691 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1692
1693 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001694 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1695 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001696 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1697 channelCount <= outputChannelCount) {
1698 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001699 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1700 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001701 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001702 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001703 currentMatchCriteria[3] = outputChannelCount;
1704 }
1705
1706 // sampling rate match
1707 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001708 samplingRate <= outputDesc->getSamplingRate()) {
1709 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001710 }
1711
1712 // performance flags match
1713 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1714
1715 // format match
1716 if (format != AUDIO_FORMAT_INVALID) {
1717 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001718 PolicyAudioPort::kFormatDistanceMax -
1719 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001720 }
1721
1722 // primary output match
1723 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1724
1725 // compare match criteria by priority then value
1726 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1727 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1728 bestMatchCriteria = currentMatchCriteria;
1729 bestOutput = output;
1730
1731 std::stringstream result;
1732 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1733 std::ostream_iterator<int>(result, " "));
1734 ALOGV("%s new bestOutput %d criteria %s",
1735 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001736 }
1737 }
1738
Eric Laurent16c66dd2019-05-01 17:54:10 -07001739 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001740}
1741
Eric Laurent8fc147b2018-07-22 19:13:55 -07001742status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001743{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001744 ALOGV("%s portId %d", __FUNCTION__, portId);
1745
1746 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1747 if (outputDesc == 0) {
1748 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001749 return BAD_VALUE;
1750 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001751 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001752
Eric Laurent8fc147b2018-07-22 19:13:55 -07001753 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001754 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001755
Eric Laurent733ce942017-12-07 12:18:25 -08001756 status_t status = outputDesc->start();
1757 if (status != NO_ERROR) {
1758 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001759 }
1760
Eric Laurent97ac8712018-07-27 18:59:02 -07001761 uint32_t delayMs;
1762 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001763
1764 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001765 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001766 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001767 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001768 if (delayMs != 0) {
1769 usleep(delayMs * 1000);
1770 }
1771
1772 return status;
1773}
1774
Eric Laurent97ac8712018-07-27 18:59:02 -07001775status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1776 const sp<TrackClientDescriptor>& client,
1777 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001778{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001779 // cannot start playback of STREAM_TTS if any other output is being used
1780 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001781
1782 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001783 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001784 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001785 auto clientStrategy = client->strategy();
1786 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001787 if (stream == AUDIO_STREAM_TTS) {
1788 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001789 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001790 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001791 return INVALID_OPERATION;
1792 } else {
1793 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1794 }
1795 } else {
1796 // some playback other than beacon starts
1797 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1798 }
1799
Eric Laurent77305a62016-07-25 16:39:22 -07001800 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001801 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001802 bool force = !outputDesc->isActive() &&
1803 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001804
François Gaffie11d30102018-11-02 16:09:09 +01001805 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001806 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001807 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001808 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001809 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001810 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001811 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001812 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001813 } else {
1814 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001815 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001816 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1817 AUDIO_FORMAT_DEFAULT);
1818 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1819 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001820 }
1821
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001822 // requiresMuteCheck is false when we can bypass mute strategy.
1823 // It covers a common case when there is no materially active audio
1824 // and muting would result in unnecessary delay and dropped audio.
1825 const uint32_t outputLatencyMs = outputDesc->latency();
1826 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1827
Eric Laurente552edb2014-03-10 17:42:56 -07001828 // increment usage count for this stream on the requested output:
1829 // NOTE that the usage count is the same for duplicated output and hardware output which is
1830 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001831 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001832
1833 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001834 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1835 client->isPreferredDeviceForExclusiveUse()) {
1836 // Preferred device may be exclusive, use only if no other active clients on this output
1837 devices = DeviceVector(
1838 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1839 } else {
1840 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1841 }
François Gaffie11d30102018-11-02 16:09:09 +01001842 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001843 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001844 }
1845 }
Eric Laurente552edb2014-03-10 17:42:56 -07001846
François Gaffiec005e562018-11-06 15:04:49 +01001847 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001848 selectOutputForMusicEffects();
1849 }
1850
François Gaffie1c878552018-11-22 16:53:21 +01001851 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001852 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001853 if (devices.isEmpty()) {
1854 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001855 }
François Gaffiec005e562018-11-06 15:04:49 +01001856 bool shouldWait =
1857 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1858 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1859 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001860 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001861 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001862 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001863 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001864 // An output has a shared device if
1865 // - managed by the same hw module
1866 // - supports the currently selected device
1867 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001868 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001869
Eric Laurent77305a62016-07-25 16:39:22 -07001870 // force a device change if any other output is:
1871 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001872 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001873 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001874 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001875 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001876 // change the device currently selected by the other output.
1877 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001878 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001879 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001880 force = true;
1881 }
1882 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001883 // a notification so that audio focus effect can propagate, or that a mute/unmute
1884 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001885 const uint32_t latencyMs = desc->latency();
1886 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1887
1888 if (shouldWait && isActive && (waitMs < latencyMs)) {
1889 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001890 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001891
1892 // Require mute check if another output is on a shared device
1893 // and currently active to have proper drain and avoid pops.
1894 // Note restoring AudioTracks onto this output needs to invoke
1895 // a volume ramp if there is no mute.
1896 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001897 }
1898 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001899
1900 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001901 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001902
Eric Laurente552edb2014-03-10 17:42:56 -07001903 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001904 auto &curves = getVolumeCurves(client->attributes());
1905 checkAndSetVolume(curves, client->volumeSource(),
1906 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001907 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001908 outputDesc->devices().types(), 0 /*delay*/,
1909 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001910
1911 // update the outputs if starting an output with a stream that can affect notification
1912 // routing
1913 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001914
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001915 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001916 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001917 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1918 }
Eric Laurentdc462862016-07-19 12:29:53 -07001919
1920 if (waitMs > muteWaitMs) {
1921 *delayMs = waitMs - muteWaitMs;
1922 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001923
1924 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1925 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1926 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1927 // change occurs after the MixerThread starts and causes a stream volume
1928 // glitch.
1929 //
1930 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001931 }
Eric Laurentdc462862016-07-19 12:29:53 -07001932
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001933 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07001934 mEngine->getForceUse(
1935 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001936 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001937 }
1938
Eric Laurent97ac8712018-07-27 18:59:02 -07001939 // Automatically enable the remote submix input when output is started on a re routing mix
1940 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07001941 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1942 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001943 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1944 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1945 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001946 "remote-submix",
1947 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001948 }
1949
Eric Laurente552edb2014-03-10 17:42:56 -07001950 return NO_ERROR;
1951}
1952
Eric Laurent8fc147b2018-07-22 19:13:55 -07001953status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001954{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001955 ALOGV("%s portId %d", __FUNCTION__, portId);
1956
1957 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1958 if (outputDesc == 0) {
1959 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001960 return BAD_VALUE;
1961 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001962 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001963
Eric Laurent97ac8712018-07-27 18:59:02 -07001964 ALOGV("stopOutput() output %d, stream %d, session %d",
1965 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001966
Eric Laurent97ac8712018-07-27 18:59:02 -07001967 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001968
Eric Laurent733ce942017-12-07 12:18:25 -08001969 if (status == NO_ERROR ) {
1970 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001971 }
1972 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001973}
1974
Eric Laurent97ac8712018-07-27 18:59:02 -07001975status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1976 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001977{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001978 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001979 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001980 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07001981
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001982 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1983
François Gaffie1c878552018-11-22 16:53:21 +01001984 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
1985 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001986 // Automatically disable the remote submix input when output is stopped on a
1987 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001988 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07001989 if (isSingleDeviceType(
1990 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001991 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001992 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001993 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1994 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001995 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001996 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001997 }
1998 }
1999 bool forceDeviceUpdate = false;
2000 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002001 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002002 forceDeviceUpdate = true;
2003 }
2004
Eric Laurente552edb2014-03-10 17:42:56 -07002005 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002006 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002007
Eric Laurente552edb2014-03-10 17:42:56 -07002008 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002009 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002010 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002011 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002012 // delay the device switch by twice the latency because stopOutput() is executed when
2013 // the track stop() command is received and at that time the audio track buffer can
2014 // still contain data that needs to be drained. The latency only covers the audio HAL
2015 // and kernel buffers. Also the latency does not always include additional delay in the
2016 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01002017 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07002018
2019 // force restoring the device selection on other active outputs if it differs from the
2020 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002021 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002022 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002023 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002024 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002025 desc->isActive() &&
2026 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002027 (newDevices != desc->devices())) {
2028 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2029 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002030
François Gaffie11d30102018-11-02 16:09:09 +01002031 setOutputDevices(desc, newDevices2, force, delayMs);
2032
Eric Laurent57de36c2016-09-28 16:59:11 -07002033 // re-apply device specific volume if not done by setOutputDevice()
2034 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002035 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002036 }
Eric Laurente552edb2014-03-10 17:42:56 -07002037 }
2038 }
2039 // update the outputs if stopping one with a stream that can affect notification routing
2040 handleNotificationRoutingForStream(stream);
2041 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002042
2043 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2044 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002045 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002046 }
2047
François Gaffiec005e562018-11-06 15:04:49 +01002048 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002049 selectOutputForMusicEffects();
2050 }
Eric Laurente552edb2014-03-10 17:42:56 -07002051 return NO_ERROR;
2052 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002053 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002054 return INVALID_OPERATION;
2055 }
2056}
2057
jiabinbce0c1d2020-10-05 11:20:18 -07002058bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002059{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002060 ALOGV("%s portId %d", __FUNCTION__, portId);
2061
2062 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2063 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002064 // If an output descriptor is closed due to a device routing change,
2065 // then there are race conditions with releaseOutput from tracks
2066 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2067 // destroyed shortly thereafter.
2068 //
2069 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002070 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002071 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002072 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002073
2074 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002075
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302076 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2077 if (outputDesc->isClientActive(client)) {
2078 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2079 stopOutput(portId);
2080 }
2081
Eric Laurent8fc147b2018-07-22 19:13:55 -07002082 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2083 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002084 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002085 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002086 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002087 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002088 if (--outputDesc->mDirectOpenCount == 0) {
2089 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002090 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002091 }
2092 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302093
Andy Hung39efb7a2018-09-26 15:39:28 -07002094 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002095 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2096 // The output is pending reopened to query dynamic profiles and
2097 // there is no active clients
2098 closeOutput(outputDesc->mIoHandle);
2099 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2100 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2101 if (newOutputDesc == nullptr) {
2102 ALOGE("%s failed to open output", __func__);
2103 }
2104 return true;
2105 }
2106 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002107}
2108
Eric Laurentcaf7f482014-11-25 17:50:47 -08002109status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2110 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002111 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002112 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002113 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002114 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002115 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002116 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002117 input_type_t *inputType,
2118 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002119{
François Gaffiec005e562018-11-06 15:04:49 +01002120 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
2121 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
2122 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002123
Eric Laurentad2e7b92017-09-14 20:06:42 -07002124 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002125 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002126 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002127 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002128 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002129 sp<AudioInputDescriptor> inputDesc;
2130 sp<RecordClientDescriptor> clientDesc;
2131 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002132 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002133
2134 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2135 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2136 return INVALID_OPERATION;
2137 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002138
Francois Gaffie716e1432019-01-14 16:58:59 +01002139 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2140 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002141 }
2142
Paul McLean466dc8e2015-04-17 13:15:36 -06002143 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01002144 sp<DeviceDescriptor> explicitRoutingDevice =
2145 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002146
Eric Laurentad2e7b92017-09-14 20:06:42 -07002147 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2148 // possible
2149 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2150 *input != AUDIO_IO_HANDLE_NONE) {
2151 ssize_t index = mInputs.indexOfKey(*input);
2152 if (index < 0) {
2153 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2154 status = BAD_VALUE;
2155 goto error;
2156 }
2157 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002158 RecordClientVector clients = inputDesc->getClientsForSession(session);
2159 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002160 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2161 status = BAD_VALUE;
2162 goto error;
2163 }
2164 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2165 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002166 // corresponds to a new client and is only permitted from the same UID.
2167 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002168 if (clients.size() > 1) {
2169 for (const auto& client : clients) {
2170 // The client map is ordered by key values (portId) and portIds are allocated
2171 // incrementaly. So the first client in this list is the one opened by audio flinger
2172 // when the mmap stream is created and should be ignored as it does not correspond
2173 // to an actual client
2174 if (client == *clients.cbegin()) {
2175 continue;
2176 }
2177 if (uid != client->uid() && !client->isSilenced()) {
2178 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2179 uid, client->portId(), client->uid());
2180 status = INVALID_OPERATION;
2181 goto error;
2182 }
Eric Laurent331679c2018-04-16 17:03:16 -07002183 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002184 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002185 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002186 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002187
Eric Laurentfecbceb2021-02-09 14:46:43 +01002188 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002189 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002190 }
2191
2192 *input = AUDIO_IO_HANDLE_NONE;
2193 *inputType = API_INPUT_INVALID;
2194
Francois Gaffie716e1432019-01-14 16:58:59 +01002195 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002196
Francois Gaffie716e1432019-01-14 16:58:59 +01002197 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2198 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2199 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002200 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002201 ALOGW("%s could not find input mix for attr %s",
2202 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002203 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002204 }
jiabinc1de2df2019-05-07 14:26:40 -07002205 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2206 String8(attr->tags + strlen("addr=")),
2207 AUDIO_FORMAT_DEFAULT);
2208 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002209 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002210 __func__, attributes.source, attributes.tags);
2211 status = BAD_VALUE;
2212 goto error;
2213 }
2214
Kevin Rocard25f9b052019-02-27 15:08:54 -08002215 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2216 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2217 } else {
2218 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2219 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002220 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002221 if (explicitRoutingDevice != nullptr) {
2222 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002223 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002224 // Prevent from storing invalid requested device id in clients
2225 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002226 device = mEngine->getInputDeviceForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07002227 }
François Gaffie11d30102018-11-02 16:09:09 +01002228 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002229 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002230 status = BAD_VALUE;
2231 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002232 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002233 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2234 *inputType = API_INPUT_MIX_CAPTURE;
2235 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002236 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2237 // there is an external policy, but this input is attached to a mix of recorders,
2238 // meaning it receives audio injected into the framework, so the recorder doesn't
2239 // know about it and is therefore considered "legacy"
2240 *inputType = API_INPUT_LEGACY;
2241 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002242 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002243 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002244 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002245 } else {
2246 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002247 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002248
Eric Laurent599c7582015-12-07 18:05:55 -08002249 }
2250
François Gaffiec005e562018-11-06 15:04:49 +01002251 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002252 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002253 status = INVALID_OPERATION;
2254 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002255 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002256
Eric Laurent8f42ea12018-08-08 09:08:25 -07002257exit:
2258
François Gaffiec005e562018-11-06 15:04:49 +01002259 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2260 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002261
Francois Gaffie716e1432019-01-14 16:58:59 +01002262 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002263 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002264 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002265
Mikhail Naganov2996f672019-04-18 12:29:59 -07002266 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002267 requestedDeviceId, attributes.source, flags,
2268 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002269 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002270 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002271
2272 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2273 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002274
Eric Laurent599c7582015-12-07 18:05:55 -08002275 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002276
2277error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002278 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002279}
2280
2281
François Gaffie11d30102018-11-02 16:09:09 +01002282audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002283 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002284 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002285 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002286 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002287 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002288{
2289 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002290 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002291 bool isSoundTrigger = false;
2292
François Gaffiec005e562018-11-06 15:04:49 +01002293 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002294 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2295 if (index >= 0) {
2296 input = mSoundTriggerSessions.valueFor(session);
2297 isSoundTrigger = true;
2298 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2299 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2300 } else {
2301 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002302 }
François Gaffiec005e562018-11-06 15:04:49 +01002303 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002304 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002305 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002306 }
2307
Andy Hungf129b032015-04-07 13:45:50 -07002308 // find a compatible input profile (not necessarily identical in parameters)
2309 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002310 // sampling rate and flags may be updated by getInputProfile
2311 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2312 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002313 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002314 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002315 audio_input_flags_t profileFlags = flags;
2316 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002317 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002318 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002319 profileFlags);
2320 if (profile != 0) {
2321 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002322 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2323 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002324 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2325 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2326 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002327 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2328 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2329 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002330 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002331 }
Eric Laurente552edb2014-03-10 17:42:56 -07002332 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002333 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002334 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002335 if (samplingRate == 0) {
2336 samplingRate = profileSamplingRate;
2337 }
Eric Laurente552edb2014-03-10 17:42:56 -07002338
Eric Laurent322b4d22015-04-03 15:57:54 -07002339 if (profile->getModuleHandle() == 0) {
2340 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002341 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002342 }
2343
Eric Laurent3974e3b2017-12-07 17:58:43 -08002344 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002345 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002346 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002347 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002348 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002349 continue;
2350 }
2351 // if sound trigger, reuse input if used by other sound trigger on same session
2352 // else
2353 // reuse input if active client app is not in IDLE state
2354 //
2355 RecordClientVector clients = desc->clientsList();
2356 bool doClose = false;
2357 for (const auto& client : clients) {
2358 if (isSoundTrigger != client->isSoundTrigger()) {
2359 continue;
2360 }
2361 if (client->isSoundTrigger()) {
2362 if (session == client->session()) {
2363 return desc->mIoHandle;
2364 }
2365 continue;
2366 }
2367 if (client->active() && client->appState() != APP_STATE_IDLE) {
2368 return desc->mIoHandle;
2369 }
2370 doClose = true;
2371 }
2372 if (doClose) {
2373 closeInput(desc->mIoHandle);
2374 } else {
2375 i++;
2376 }
2377 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002378 }
2379
Eric Laurentfe231122017-11-17 17:48:06 -08002380 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002381
Eric Laurentfe231122017-11-17 17:48:06 -08002382 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2383 lConfig.sample_rate = profileSamplingRate;
2384 lConfig.channel_mask = profileChannelMask;
2385 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002386
François Gaffie11d30102018-11-02 16:09:09 +01002387 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002388
2389 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002390 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002391 (profileSamplingRate != lConfig.sample_rate) ||
2392 !audio_formats_match(profileFormat, lConfig.format) ||
2393 (profileChannelMask != lConfig.channel_mask)) {
2394 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002395 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002396 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002397 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002398 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002399 }
Eric Laurent599c7582015-12-07 18:05:55 -08002400 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002401 }
2402
Eric Laurentc722f302014-12-10 11:21:49 -08002403 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002404
Eric Laurent599c7582015-12-07 18:05:55 -08002405 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002406 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002407
Eric Laurent599c7582015-12-07 18:05:55 -08002408 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002409}
2410
Eric Laurent4eb58f12018-12-07 16:41:02 -08002411status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002412{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002413 ALOGV("%s portId %d", __FUNCTION__, portId);
2414
2415 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2416 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002417 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002418 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002419 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002420 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002421 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002422 if (client->active()) {
2423 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2424 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002425 }
2426
Eric Laurent8f42ea12018-08-08 09:08:25 -07002427 audio_session_t session = client->session();
2428
Eric Laurent4eb58f12018-12-07 16:41:02 -08002429 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002430
Eric Laurent4eb58f12018-12-07 16:41:02 -08002431 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002432
Eric Laurent4eb58f12018-12-07 16:41:02 -08002433 status_t status = inputDesc->start();
2434 if (status != NO_ERROR) {
2435 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002436 }
Eric Laurente552edb2014-03-10 17:42:56 -07002437
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002438 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002439 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002440 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002441
Eric Laurent8f42ea12018-08-08 09:08:25 -07002442 // indicate active capture to sound trigger service if starting capture from a mic on
2443 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002444 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002445 if (device != nullptr) {
2446 status = setInputDevice(input, device, true /* force */);
2447 } else {
2448 ALOGW("%s no new input device can be found for descriptor %d",
2449 __FUNCTION__, inputDesc->getId());
2450 status = BAD_VALUE;
2451 }
Eric Laurente552edb2014-03-10 17:42:56 -07002452
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002453 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
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_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002460 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002461
François Gaffie11d30102018-11-02 16:09:09 +01002462 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2463 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002464 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002465 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002466 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002467
Eric Laurent8f42ea12018-08-08 09:08:25 -07002468 // automatically enable the remote submix output when input is started if not
2469 // used by a policy mix of type MIX_TYPE_RECORDERS
2470 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002471 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002472 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002473 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002474 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002475 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2476 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002477 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002478 if (address != "") {
2479 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2480 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002481 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002482 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002483 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002484 } else if (status != NO_ERROR) {
2485 // Restore client activity state.
2486 inputDesc->setClientActive(client, false);
2487 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002488 }
2489
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002490 ALOGV("%s input %d source = %d status = %d exit",
2491 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002492
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002493 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002494}
2495
Eric Laurent8fc147b2018-07-22 19:13:55 -07002496status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002497{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002498 ALOGV("%s portId %d", __FUNCTION__, portId);
2499
2500 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2501 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002502 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002503 return BAD_VALUE;
2504 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002505 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002506 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002507 if (!client->active()) {
2508 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002509 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002510 }
2511
Eric Laurent8f42ea12018-08-08 09:08:25 -07002512 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002513
Eric Laurent8f42ea12018-08-08 09:08:25 -07002514 inputDesc->stop();
2515 if (inputDesc->isActive()) {
2516 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2517 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002518 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002519 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002520 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002521 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2522 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002523 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002524 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002525
2526 // automatically disable the remote submix output when input is stopped if not
2527 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002528 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002529 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002530 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002531 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002532 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2533 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002534 }
2535 if (address != "") {
2536 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2537 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002538 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002539 }
2540 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002541 resetInputDevice(input);
2542
2543 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2544 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002545 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2546 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002547 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002548 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002549 }
2550 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002551 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002552 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002553}
2554
Eric Laurent8fc147b2018-07-22 19:13:55 -07002555void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002556{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002557 ALOGV("%s portId %d", __FUNCTION__, portId);
2558
2559 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2560 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002561 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002562 return;
2563 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002564 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002565 audio_io_handle_t input = inputDesc->mIoHandle;
2566
Eric Laurent8f42ea12018-08-08 09:08:25 -07002567 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002568
Andy Hung39efb7a2018-09-26 15:39:28 -07002569 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002570
Andy Hung39efb7a2018-09-26 15:39:28 -07002571 if (inputDesc->getClientCount() > 0) {
2572 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002573 return;
2574 }
2575
Eric Laurent05b90f82014-08-27 15:32:29 -07002576 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002577 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002578 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002579}
2580
Eric Laurent8f42ea12018-08-08 09:08:25 -07002581void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002582{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002583 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002584
2585 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002586 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002587 }
2588}
2589
Eric Laurent8f42ea12018-08-08 09:08:25 -07002590void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2591{
2592 stopInput(portId);
2593 releaseInput(portId);
2594}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002595
Eric Laurent0dd51852019-04-19 18:18:58 -07002596void AudioPolicyManager::checkCloseInputs() {
2597 // After connecting or disconnecting an input device, close input if:
2598 // - it has no client (was just opened to check profile) OR
2599 // - none of its supported devices are connected anymore OR
2600 // - one of its clients cannot be routed to one of its supported
2601 // devices anymore. Otherwise update device selection
2602 std::vector<audio_io_handle_t> inputsToClose;
2603 for (size_t i = 0; i < mInputs.size(); i++) {
2604 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2605 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002606 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002607 inputsToClose.push_back(mInputs.keyAt(i));
2608 } else {
2609 bool close = false;
2610 for (const auto& client : input->clientsList()) {
2611 sp<DeviceDescriptor> device =
2612 mEngine->getInputDeviceForAttributes(client->attributes());
2613 if (!input->supportedDevices().contains(device)) {
2614 close = true;
2615 break;
2616 }
2617 }
2618 if (close) {
2619 inputsToClose.push_back(mInputs.keyAt(i));
2620 } else {
2621 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2622 }
2623 }
2624 }
2625
2626 for (const audio_io_handle_t handle : inputsToClose) {
2627 ALOGV("%s closing input %d", __func__, handle);
2628 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002629 }
Eric Laurentd4692962014-05-05 18:13:44 -07002630}
2631
François Gaffie251c7f02018-11-07 10:41:08 +01002632void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002633{
2634 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002635 if (indexMin < 0 || indexMax < 0) {
2636 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2637 return;
2638 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002639 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002640
2641 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002642 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2643 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002644 continue;
2645 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002646 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002647 }
Eric Laurente552edb2014-03-10 17:42:56 -07002648}
2649
Eric Laurente0720872014-03-11 09:30:41 -07002650status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002651 int index,
2652 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002653{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002654 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002655 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2656 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2657 return NO_ERROR;
2658 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002659 ALOGV("%s: stream %s attributes=%s", __func__,
2660 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002661 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002662}
2663
Eric Laurente0720872014-03-11 09:30:41 -07002664status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002665 int *index,
2666 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002667{
François Gaffiec005e562018-11-06 15:04:49 +01002668 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2669 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002670 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002671 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002672 deviceTypes = mEngine->getOutputDevicesForStream(
2673 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002674 }
jiabin9a3361e2019-10-01 09:38:30 -07002675 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002676}
2677
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002678status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002679 int index,
2680 audio_devices_t device)
2681{
2682 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002683 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2684 if (group == VOLUME_GROUP_NONE) {
2685 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002686 return BAD_VALUE;
2687 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002688 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002689 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002690 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002691 VolumeSource vs = toVolumeSource(group);
2692 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2693
2694 status = setVolumeCurveIndex(index, device, curves);
2695 if (status != NO_ERROR) {
2696 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2697 return status;
2698 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002699
jiabin9a3361e2019-10-01 09:38:30 -07002700 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002701 auto curCurvAttrs = curves.getAttributes();
2702 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2703 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002704 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002705 } else if (!curves.getStreamTypes().empty()) {
2706 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002707 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002708 } else {
2709 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2710 return BAD_VALUE;
2711 }
jiabin9a3361e2019-10-01 09:38:30 -07002712 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2713 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002714
François Gaffiecfe17322018-11-07 13:41:29 +01002715 // update volume on all outputs and streams matching the following:
2716 // - The requested stream (or a stream matching for volume control) is active on the output
2717 // - The device (or devices) selected by the engine for this stream includes
2718 // the requested device
2719 // - For non default requested device, currently selected device on the output is either the
2720 // requested device or one of the devices selected by the engine for this stream
2721 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2722 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002723 for (size_t i = 0; i < mOutputs.size(); i++) {
2724 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002725 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002726
jiabin9a3361e2019-10-01 09:38:30 -07002727 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2728 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002729 }
François Gaffieed91f582020-01-31 10:35:37 +01002730 if (!(desc->isActive(vs) || isInCall())) {
2731 continue;
2732 }
2733 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2734 curDevices.find(device) == curDevices.end()) {
2735 continue;
2736 }
2737 bool applyVolume = false;
2738 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2739 curSrcDevices.insert(device);
2740 applyVolume = (curSrcDevices.find(
2741 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2742 } else {
2743 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2744 }
2745 if (!applyVolume) {
2746 continue; // next output
2747 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002748 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2749 // If a higher priority strategy is active, and the output is routed to a device with a
2750 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002751 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002752 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002753 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2754 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2755 false /*preferredDevice*/);
2756 if (activeClients.empty()) {
2757 continue;
2758 }
2759 bool isPreempted = false;
2760 bool isHigherPriority = productStrategy < strategy;
2761 for (const auto &client : activeClients) {
2762 if (isHigherPriority && (client->volumeSource() != vs)) {
2763 ALOGV("%s: Strategy=%d (\nrequester:\n"
2764 " group %d, volumeGroup=%d attributes=%s)\n"
2765 " higher priority source active:\n"
2766 " volumeGroup=%d attributes=%s) \n"
2767 " on output %zu, bailing out", __func__, productStrategy,
2768 group, group, toString(attributes).c_str(),
2769 client->volumeSource(), toString(client->attributes()).c_str(), i);
2770 applyVolume = false;
2771 isPreempted = true;
2772 break;
2773 }
2774 // However, continue for loop to ensure no higher prio clients running on output
2775 if (client->volumeSource() == vs) {
2776 applyVolume = true;
2777 }
2778 }
2779 if (isPreempted || applyVolume) {
2780 break;
2781 }
2782 }
2783 if (!applyVolume) {
2784 continue; // next output
2785 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002786 }
François Gaffieed91f582020-01-31 10:35:37 +01002787 //FIXME: workaround for truncated touch sounds
2788 // delayed volume change for system stream to be removed when the problem is
2789 // handled by system UI
2790 status_t volStatus = checkAndSetVolume(
2791 curves, vs, index, desc, curDevices,
2792 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2793 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2794 if (volStatus != NO_ERROR) {
2795 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002796 }
2797 }
François Gaffiecfe17322018-11-07 13:41:29 +01002798 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2799 return status;
2800}
2801
François Gaffieaaac0fd2018-11-22 17:56:39 +01002802status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002803 audio_devices_t device,
2804 IVolumeCurves &volumeCurves)
2805{
2806 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2807 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002808 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2809 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002810 (index > volumeCurves.getVolumeIndexMax())) {
2811 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2812 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2813 return BAD_VALUE;
2814 }
2815 if (!audio_is_output_device(device)) {
2816 return BAD_VALUE;
2817 }
2818
2819 // Force max volume if stream cannot be muted
2820 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2821
François Gaffieaaac0fd2018-11-22 17:56:39 +01002822 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002823 volumeCurves.addCurrentVolumeIndex(device, index);
2824 return NO_ERROR;
2825}
2826
2827status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2828 int &index,
2829 audio_devices_t device)
2830{
2831 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2832 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002833 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002834 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002835 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2836 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002837 }
jiabin9a3361e2019-10-01 09:38:30 -07002838 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002839}
2840
2841status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2842 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002843 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002844{
jiabin9a3361e2019-10-01 09:38:30 -07002845 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002846 return BAD_VALUE;
2847 }
jiabin9a3361e2019-10-01 09:38:30 -07002848 index = curves.getVolumeIndex(deviceTypes);
2849 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002850 return NO_ERROR;
2851}
2852
2853status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2854 int &index)
2855{
2856 index = getVolumeCurves(attr).getVolumeIndexMin();
2857 return NO_ERROR;
2858}
2859
2860status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2861 int &index)
2862{
2863 index = getVolumeCurves(attr).getVolumeIndexMax();
2864 return NO_ERROR;
2865}
2866
Eric Laurent36829f92017-04-07 19:04:42 -07002867audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002868{
2869 // select one output among several suitable for global effects.
2870 // The priority is as follows:
2871 // 1: An offloaded output. If the effect ends up not being offloadable,
2872 // AudioFlinger will invalidate the track and the offloaded output
2873 // will be closed causing the effect to be moved to a PCM output.
2874 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002875 // 3: The primary output
2876 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002877
François Gaffiec005e562018-11-06 15:04:49 +01002878 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2879 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002880 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002881
Eric Laurent36829f92017-04-07 19:04:42 -07002882 if (outputs.size() == 0) {
2883 return AUDIO_IO_HANDLE_NONE;
2884 }
Eric Laurente552edb2014-03-10 17:42:56 -07002885
Eric Laurent36829f92017-04-07 19:04:42 -07002886 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2887 bool activeOnly = true;
2888
2889 while (output == AUDIO_IO_HANDLE_NONE) {
2890 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2891 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2892 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2893
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002894 for (audio_io_handle_t output : outputs) {
2895 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002896 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002897 continue;
2898 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002899 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2900 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002901 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002902 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002903 }
2904 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002905 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002906 }
2907 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002908 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002909 }
2910 }
2911 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2912 output = outputOffloaded;
2913 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2914 output = outputDeepBuffer;
2915 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2916 output = outputPrimary;
2917 } else {
2918 output = outputs[0];
2919 }
2920 activeOnly = false;
2921 }
2922
2923 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002924 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002925 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2926 mMusicEffectOutput = output;
2927 }
2928
2929 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002930 return output;
2931}
2932
Eric Laurent36829f92017-04-07 19:04:42 -07002933audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2934{
2935 return selectOutputForMusicEffects();
2936}
2937
Eric Laurente0720872014-03-11 09:30:41 -07002938status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002939 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002940 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07002941 int session,
2942 int id)
2943{
Eric Laurentb82e6b72019-11-22 17:25:04 -08002944 if (session != AUDIO_SESSION_DEVICE) {
2945 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07002946 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08002947 index = mInputs.indexOfKey(io);
2948 if (index < 0) {
2949 ALOGW("registerEffect() unknown io %d", io);
2950 return INVALID_OPERATION;
2951 }
Eric Laurente552edb2014-03-10 17:42:56 -07002952 }
2953 }
François Gaffiec005e562018-11-06 15:04:49 +01002954 return mEffects.registerEffect(desc, io, session, id,
2955 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
2956 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07002957}
2958
Eric Laurentc241b0d2018-11-28 09:08:49 -08002959status_t AudioPolicyManager::unregisterEffect(int id)
2960{
2961 if (mEffects.getEffect(id) == nullptr) {
2962 return INVALID_OPERATION;
2963 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08002964 if (mEffects.isEffectEnabled(id)) {
2965 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2966 setEffectEnabled(id, false);
2967 }
2968 return mEffects.unregisterEffect(id);
2969}
2970
2971status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2972{
2973 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2974 if (effect == nullptr) {
2975 return INVALID_OPERATION;
2976 }
2977
2978 status_t status = mEffects.setEffectEnabled(id, enabled);
2979 if (status == NO_ERROR) {
2980 mInputs.trackEffectEnabled(effect, enabled);
2981 }
2982 return status;
2983}
2984
Eric Laurent6c796322019-04-09 14:13:17 -07002985
2986status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
2987{
2988 mEffects.moveEffects(ids, io);
2989 return NO_ERROR;
2990}
2991
Eric Laurentc75307b2015-03-17 15:29:32 -07002992bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2993{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002994 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002995}
2996
2997bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2998{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002999 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003000}
3001
Eric Laurente0720872014-03-11 09:30:41 -07003002bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003003{
3004 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003005 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003006 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003007 return true;
3008 }
3009 }
3010 return false;
3011}
3012
Eric Laurent275e8e92014-11-30 15:14:47 -08003013// Register a list of custom mixes with their attributes and format.
3014// When a mix is registered, corresponding input and output profiles are
3015// added to the remote submix hw module. The profile contains only the
3016// parameters (sampling rate, format...) specified by the mix.
3017// The corresponding input remote submix device is also connected.
3018//
3019// When a remote submix device is connected, the address is checked to select the
3020// appropriate profile and the corresponding input or output stream is opened.
3021//
3022// When capture starts, getInputForAttr() will:
3023// - 1 look for a mix matching the address passed in attribtutes tags if any
3024// - 2 if none found, getDeviceForInputSource() will:
3025// - 2.1 look for a mix matching the attributes source
3026// - 2.2 if none found, default to device selection by policy rules
3027// At this time, the corresponding output remote submix device is also connected
3028// and active playback use cases can be transferred to this mix if needed when reconnecting
3029// after AudioTracks are invalidated
3030//
3031// When playback starts, getOutputForAttr() will:
3032// - 1 look for a mix matching the address passed in attribtutes tags if any
3033// - 2 if none found, look for a mix matching the attributes usage
3034// - 3 if none found, default to device and output selection by policy rules.
3035
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003036status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003037{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003038 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3039 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003040 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003041 sp<HwModule> rSubmixModule;
3042 // examine each mix's route type
3043 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003044 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003045 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3046 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3047 ALOGE("Unsupported Policy Mix %zu of %zu: "
3048 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3049 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003050 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003051 break;
3052 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003053 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3054 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003055 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003056 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3057 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003058 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003059 rSubmixModule = mHwModules.getModuleFromName(
3060 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3061 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003062 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003063 i);
3064 res = INVALID_OPERATION;
3065 break;
3066 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003067 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003068
Eric Laurent97ac8712018-07-27 18:59:02 -07003069 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003070 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003071 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003072 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003073 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3074 } else {
3075 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3076 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003077 }
François Gaffie036e1e92015-03-19 10:16:24 +01003078
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003079 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003080 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003081 res = INVALID_OPERATION;
3082 break;
3083 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003084 audio_config_t outputConfig = mix.mFormat;
3085 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003086 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3087 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003088 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3089 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003090 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003091 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003092 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003093 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003094
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003095 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003096 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3097 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3098 ALOGE("Failed to set remote submix device available, type %u, address %s",
3099 mix.mDeviceType, address.string());
3100 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003101 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003102 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3103 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003104 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003105 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003106 i, mixes.size(), type, address.string());
3107
3108 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3109 mix.mDeviceType, mix.mDeviceAddress,
3110 String8(), AUDIO_FORMAT_DEFAULT);
3111 if (device == nullptr) {
3112 res = INVALID_OPERATION;
3113 break;
3114 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003115
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003116 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003117 // First try to find an already opened output supporting the device
3118 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003119 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003120
Eric Laurentc529cf62020-04-17 18:19:10 -07003121 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003122 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003123 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3124 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003125 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003126 } else {
3127 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003128 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003129 }
3130 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003131 // If no output found, try to find a direct output profile supporting the device
3132 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3133 sp<HwModule> module = mHwModules[i];
3134 for (size_t j = 0;
3135 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3136 j++) {
3137 sp<IOProfile> profile = module->getOutputProfiles()[j];
3138 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3139 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3140 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3141 address.string());
3142 res = INVALID_OPERATION;
3143 } else {
3144 foundOutput = true;
3145 }
3146 }
3147 }
3148 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003149 if (res != NO_ERROR) {
3150 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003151 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003152 res = INVALID_OPERATION;
3153 break;
3154 } else if (!foundOutput) {
3155 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003156 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003157 res = INVALID_OPERATION;
3158 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003159 } else {
3160 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003161 }
Eric Laurentc722f302014-12-10 11:21:49 -08003162 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003163 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003164 if (res != NO_ERROR) {
3165 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003166 } else if (checkOutputs) {
3167 checkForDeviceAndOutputChanges();
3168 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003169 }
3170 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003171}
3172
3173status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3174{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003175 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003176 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003177 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003178 sp<HwModule> rSubmixModule;
3179 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003180 for (const auto& mix : mixes) {
3181 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003182
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003183 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003184 rSubmixModule = mHwModules.getModuleFromName(
3185 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3186 if (rSubmixModule == 0) {
3187 res = INVALID_OPERATION;
3188 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003189 }
3190 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003191
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003192 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003193
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003194 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003195 res = INVALID_OPERATION;
3196 continue;
3197 }
3198
Kevin Rocard04ed0462019-05-02 17:53:24 -07003199 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3200 if (getDeviceConnectionState(device, address.string()) ==
3201 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3202 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3203 address.string(), "remote-submix",
3204 AUDIO_FORMAT_DEFAULT);
3205 if (res != OK) {
3206 ALOGE("Error making RemoteSubmix device unavailable for mix "
3207 "with type %d, address %s", device, address.string());
3208 }
3209 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003210 }
jiabin5740f082019-08-19 15:08:30 -07003211 rSubmixModule->removeOutputProfile(address.c_str());
3212 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003213
Kevin Rocard153f92d2018-12-18 18:33:28 -08003214 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003215 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003216 res = INVALID_OPERATION;
3217 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003218 } else {
3219 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003220 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003221 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003222 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003223 if (res == NO_ERROR && checkOutputs) {
3224 checkForDeviceAndOutputChanges();
3225 updateCallAndOutputRouting();
3226 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003227 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003228}
3229
Mikhail Naganov100f0122018-11-29 11:22:16 -08003230void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3231{
3232 size_t i = 0;
3233 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3234 for (const auto& fmt : mManualSurroundFormats) {
3235 if (i++ != 0) dst->append(", ");
3236 std::string sfmt;
3237 FormatConverter::toString(fmt, sfmt);
3238 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3239 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3240 }
3241}
3242
Eric Laurentc529cf62020-04-17 18:19:10 -07003243// Returns true if all devices types match the predicate and are supported by one HW module
3244bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003245 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003246 std::function<bool(audio_devices_t)> predicate,
3247 const char *context) {
3248 for (size_t i = 0; i < devices.size(); i++) {
3249 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003250 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003251 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003252 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003253 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003254 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003255 return false;
3256 }
3257 }
3258 return true;
3259}
3260
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003261status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003262 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003263 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003264 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3265 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003266 }
3267 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003268 if (res != NO_ERROR) {
3269 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3270 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003271 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003272
3273 checkForDeviceAndOutputChanges();
3274 updateCallAndOutputRouting();
3275
3276 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003277}
3278
3279status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3280 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003281 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3282 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003283 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003284 __FUNCTION__, uid);
3285 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003286 }
3287
Eric Laurentc529cf62020-04-17 18:19:10 -07003288 checkForDeviceAndOutputChanges();
3289 updateCallAndOutputRouting();
3290
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003291 return res;
3292}
3293
Eric Laurent2517af32020-11-25 15:31:27 +01003294
jiabin0a488932020-08-07 17:32:40 -07003295status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3296 device_role_t role,
3297 const AudioDeviceTypeAddrVector &devices) {
3298 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3299 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003300
Eric Laurentc529cf62020-04-17 18:19:10 -07003301 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003302 return BAD_VALUE;
3303 }
jiabin0a488932020-08-07 17:32:40 -07003304 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003305 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003306 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3307 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003308 return status;
3309 }
3310
3311 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-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 Trivi30857152019-11-01 11:04:15 -07003323
3324 return NO_ERROR;
3325}
3326
3327void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3328{
3329 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003330 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003331 // Only apply special touch sound delay once
3332 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003333 }
3334 for (size_t i = 0; i < mOutputs.size(); i++) {
3335 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3336 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3337 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3338 // As done in setDeviceConnectionState, we could also fix default device issue by
3339 // preventing the force re-routing in case of default dev that distinguishes on address.
3340 // Let's give back to engine full device choice decision however.
3341 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003342 // Only apply special touch sound delay once
3343 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003344 }
3345 if (forceVolumeReeval && !newDevices.isEmpty()) {
3346 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3347 }
3348 }
3349}
3350
Eric Laurent2517af32020-11-25 15:31:27 +01003351void AudioPolicyManager::updateInputRouting() {
3352 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303353 // Skip for hotword recording as the input device switch
3354 // is handled within sound trigger HAL
3355 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3356 continue;
3357 }
Eric Laurent2517af32020-11-25 15:31:27 +01003358 auto newDevice = getNewInputDevice(activeDesc);
3359 // Force new input selection if the new device can not be reached via current input
3360 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3361 setInputDevice(activeDesc->mIoHandle, newDevice);
3362 } else {
3363 closeInput(activeDesc->mIoHandle);
3364 }
3365 }
3366}
3367
jiabin0a488932020-08-07 17:32:40 -07003368status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3369 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003370{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003371 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003372
jiabin0a488932020-08-07 17:32:40 -07003373 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003374 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003375 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3376 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003377 return status;
3378 }
3379
3380 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003381
3382 bool forceVolumeReeval = false;
3383 // FIXME: workaround for truncated touch sounds
3384 // to be removed when the problem is handled by system UI
3385 uint32_t delayMs = 0;
3386 if (strategy == mCommunnicationStrategy) {
3387 forceVolumeReeval = true;
3388 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3389 updateInputRouting();
3390 }
3391 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003392
3393 return NO_ERROR;
3394}
3395
jiabin0a488932020-08-07 17:32:40 -07003396status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3397 device_role_t role,
3398 AudioDeviceTypeAddrVector &devices) {
3399 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003400}
3401
Jiabin Huang3b98d322020-09-03 17:54:16 +00003402status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3403 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3404 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3405 dumpAudioDeviceTypeAddrVector(devices).c_str());
3406
Mikhail Naganov55773032020-10-01 15:08:13 -07003407 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003408 return BAD_VALUE;
3409 }
3410 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3411 ALOGW_IF(status != NO_ERROR,
3412 "Engine could not set preferred devices %s for audio source %d role %d",
3413 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3414
3415 return status;
3416}
3417
3418status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3419 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3420 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3421 dumpAudioDeviceTypeAddrVector(devices).c_str());
3422
Mikhail Naganov55773032020-10-01 15:08:13 -07003423 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003424 return BAD_VALUE;
3425 }
3426 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3427 ALOGW_IF(status != NO_ERROR,
3428 "Engine could not add preferred devices %s for audio source %d role %d",
3429 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3430
Eric Laurent2517af32020-11-25 15:31:27 +01003431 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003432 return status;
3433}
3434
3435status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3436 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3437{
3438 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3439 dumpAudioDeviceTypeAddrVector(devices).c_str());
3440
Mikhail Naganov55773032020-10-01 15:08:13 -07003441 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003442 return BAD_VALUE;
3443 }
3444
3445 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3446 audioSource, role, devices);
3447 ALOGW_IF(status != NO_ERROR,
3448 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3449
Eric Laurent2517af32020-11-25 15:31:27 +01003450 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003451 return status;
3452}
3453
3454status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3455 device_role_t role) {
3456 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3457
3458 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3459 ALOGW_IF(status != NO_ERROR,
3460 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3461
Eric Laurent2517af32020-11-25 15:31:27 +01003462 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003463 return status;
3464}
3465
3466status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3467 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3468 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3469}
3470
Oscar Azucena90e77632019-11-27 17:12:28 -08003471status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003472 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003473 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003474 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3475 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003476 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003477 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3478 if (status != NO_ERROR) {
3479 ALOGE("%s() could not set device affinity for userId %d",
3480 __FUNCTION__, userId);
3481 return status;
3482 }
3483
3484 // reevaluate outputs for all devices
3485 checkForDeviceAndOutputChanges();
3486 updateCallAndOutputRouting();
3487
3488 return NO_ERROR;
3489}
3490
3491status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003492 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003493 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3494 if (status != NO_ERROR) {
3495 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3496 __FUNCTION__, userId);
3497 return status;
3498 }
3499
3500 // reevaluate outputs for all devices
3501 checkForDeviceAndOutputChanges();
3502 updateCallAndOutputRouting();
3503
3504 return NO_ERROR;
3505}
3506
Andy Hungc29d82b2018-10-05 12:23:17 -07003507void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003508{
Andy Hungc29d82b2018-10-05 12:23:17 -07003509 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3510 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003511 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003512 std::string stateLiteral;
3513 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003514 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003515 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3516 "communications", "media", "record", "dock", "system",
3517 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3518 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3519 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003520 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3521 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3522 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3523 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3524 dst->append(" (MANUAL: ");
3525 dumpManualSurroundFormats(dst);
3526 dst->append(")");
3527 }
3528 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003529 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003530 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3531 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003532 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003533 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003534
Andy Hungc29d82b2018-10-05 12:23:17 -07003535 mAvailableOutputDevices.dump(dst, String8("Available output"));
3536 mAvailableInputDevices.dump(dst, String8("Available input"));
3537 mHwModulesAll.dump(dst);
3538 mOutputs.dump(dst);
3539 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003540 mEffects.dump(dst);
3541 mAudioPatches.dump(dst);
3542 mPolicyMixes.dump(dst);
3543 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003544
Kevin Rocardb99cc752019-03-21 20:52:24 -07003545 dst->appendFormat(" AllowedCapturePolicies:\n");
3546 for (auto& policy : mAllowedCapturePolicies) {
3547 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3548 }
3549
François Gaffiec005e562018-11-06 15:04:49 +01003550 dst->appendFormat("\nPolicy Engine dump:\n");
3551 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003552}
3553
3554status_t AudioPolicyManager::dump(int fd)
3555{
3556 String8 result;
3557 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003558 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003559 return NO_ERROR;
3560}
3561
Kevin Rocardb99cc752019-03-21 20:52:24 -07003562status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3563{
3564 mAllowedCapturePolicies[uid] = capturePolicy;
3565 return NO_ERROR;
3566}
3567
Eric Laurente552edb2014-03-10 17:42:56 -07003568// This function checks for the parameters which can be offloaded.
3569// This can be enhanced depending on the capability of the DSP and policy
3570// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003571audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003572{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003573 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003574 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003575 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003576 offloadInfo.format,
3577 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3578 offloadInfo.has_video);
3579
Andy Hung2ddee192015-12-18 17:34:44 -08003580 if (mMasterMono) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003581 return AUDIO_OFFLOAD_NOT_SUPPORTED; // no offloading if mono is set.
Andy Hung2ddee192015-12-18 17:34:44 -08003582 }
3583
Eric Laurente552edb2014-03-10 17:42:56 -07003584 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003585 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003586 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3587 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003588 }
3589
3590 // Check if stream type is music, then only allow offload as of now.
3591 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3592 {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003593 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3594 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003595 }
3596
3597 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003598 const bool allowOffloadWithVideo =
3599 property_get_bool("audio.offload.video", false /* default_value */);
3600 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003601 ALOGV("%s: has_video == true, returning false", __func__);
3602 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003603 }
3604
3605 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003606 const int min_duration_secs = property_get_int32(
3607 "audio.offload.min.duration.secs", -1 /* default_value */);
3608 if (min_duration_secs >= 0) {
3609 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003610 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3611 __func__, min_duration_secs);
3612 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003613 }
3614 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003615 ALOGV("%s: Offload denied by duration < default min(=%u)",
3616 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3617 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003618 }
3619
3620 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3621 // creating an offloaded track and tearing it down immediately after start when audioflinger
3622 // detects there is an active non offloadable effect.
3623 // FIXME: We should check the audio session here but we do not have it in this context.
3624 // This may prevent offloading in rare situations where effects are left active by apps
3625 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003626 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003627 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003628 }
3629
3630 // See if there is a profile to support this.
3631 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003632 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003633 offloadInfo.sample_rate,
3634 offloadInfo.format,
3635 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003636 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3637 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003638 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3639 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3640 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003641 if (profile == nullptr) {
3642 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3643 }
3644 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3645 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3646 }
3647 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003648}
3649
Michael Chana94fbb22018-04-24 14:31:19 +10003650bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3651 const audio_attributes_t& attributes) {
3652 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003653 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003654 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003655 config.sample_rate,
3656 config.format,
3657 config.channel_mask,
3658 output_flags,
3659 true /* directOnly */);
3660 ALOGV("%s() profile %sfound with name: %s, "
3661 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3662 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003663 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003664 config.sample_rate, config.format, config.channel_mask, output_flags);
3665 return (profile != 0);
3666}
3667
Eric Laurent6a94d692014-05-20 11:18:06 -07003668status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3669 audio_port_type_t type,
3670 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003671 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003672 unsigned int *generation)
3673{
jiabin19cdba52020-11-24 11:28:58 -08003674 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3675 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003676 return BAD_VALUE;
3677 }
3678 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003679 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003680 *num_ports = 0;
3681 }
3682
3683 size_t portsWritten = 0;
3684 size_t portsMax = *num_ports;
3685 *num_ports = 0;
3686 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003687 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3688 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003689 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003690 for (const auto& dev : mAvailableOutputDevices) {
3691 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003692 continue;
3693 }
3694 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003695 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003696 }
3697 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003698 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003699 }
3700 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003701 for (const auto& dev : mAvailableInputDevices) {
3702 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003703 continue;
3704 }
3705 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003706 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003707 }
3708 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003709 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003710 }
3711 }
3712 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3713 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3714 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3715 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3716 }
3717 *num_ports += mInputs.size();
3718 }
3719 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003720 size_t numOutputs = 0;
3721 for (size_t i = 0; i < mOutputs.size(); i++) {
3722 if (!mOutputs[i]->isDuplicated()) {
3723 numOutputs++;
3724 if (portsWritten < portsMax) {
3725 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3726 }
3727 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003728 }
Eric Laurent84c70242014-06-23 08:46:27 -07003729 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003730 }
3731 }
3732 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003733 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003734 return NO_ERROR;
3735}
3736
jiabin19cdba52020-11-24 11:28:58 -08003737status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003738{
Eric Laurent99fcae42018-05-17 16:59:18 -07003739 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3740 return BAD_VALUE;
3741 }
3742 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3743 if (dev != 0) {
3744 dev->toAudioPort(port);
3745 return NO_ERROR;
3746 }
3747 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3748 if (dev != 0) {
3749 dev->toAudioPort(port);
3750 return NO_ERROR;
3751 }
3752 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3753 if (out != 0) {
3754 out->toAudioPort(port);
3755 return NO_ERROR;
3756 }
3757 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3758 if (in != 0) {
3759 in->toAudioPort(port);
3760 return NO_ERROR;
3761 }
3762 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003763}
3764
François Gaffieafd4cea2019-11-18 15:50:22 +01003765status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3766 audio_patch_handle_t *handle,
3767 uid_t uid, uint32_t delayMs,
3768 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003769{
François Gaffieafd4cea2019-11-18 15:50:22 +01003770 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003771 if (handle == NULL || patch == NULL) {
3772 return BAD_VALUE;
3773 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003774 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003775
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003776 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003777 return BAD_VALUE;
3778 }
3779 // only one source per audio patch supported for now
3780 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003781 return INVALID_OPERATION;
3782 }
Eric Laurent874c42872014-08-08 15:13:39 -07003783
3784 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003785 return INVALID_OPERATION;
3786 }
Eric Laurent874c42872014-08-08 15:13:39 -07003787 for (size_t i = 0; i < patch->num_sinks; i++) {
3788 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3789 return INVALID_OPERATION;
3790 }
3791 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003792
3793 sp<AudioPatch> patchDesc;
3794 ssize_t index = mAudioPatches.indexOfKey(*handle);
3795
François Gaffieafd4cea2019-11-18 15:50:22 +01003796 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3797 patch->sources[0].role,
3798 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003799#if LOG_NDEBUG == 0
3800 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003801 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3802 patch->sinks[i].role,
3803 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003804 }
3805#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003806
3807 if (index >= 0) {
3808 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003809 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3810 __func__, mUidCached, patchDesc->getUid(), uid);
3811 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003812 return INVALID_OPERATION;
3813 }
3814 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003815 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003816 }
3817
3818 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003819 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003820 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003821 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003822 return BAD_VALUE;
3823 }
Eric Laurent84c70242014-06-23 08:46:27 -07003824 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3825 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003826 if (patchDesc != 0) {
3827 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003828 ALOGV("%s source id differs for patch current id %d new id %d",
3829 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003830 return BAD_VALUE;
3831 }
3832 }
Eric Laurent874c42872014-08-08 15:13:39 -07003833 DeviceVector devices;
3834 for (size_t i = 0; i < patch->num_sinks; i++) {
3835 // Only support mix to devices connection
3836 // TODO add support for mix to mix connection
3837 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003838 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003839 return INVALID_OPERATION;
3840 }
3841 sp<DeviceDescriptor> devDesc =
3842 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3843 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003844 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003845 return BAD_VALUE;
3846 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003847
François Gaffie11d30102018-11-02 16:09:09 +01003848 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003849 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003850 NULL, // updatedSamplingRate
3851 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003852 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003853 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003854 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003855 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003856 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003857 return INVALID_OPERATION;
3858 }
3859 devices.add(devDesc);
3860 }
3861 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003862 return INVALID_OPERATION;
3863 }
Eric Laurent874c42872014-08-08 15:13:39 -07003864
Eric Laurent6a94d692014-05-20 11:18:06 -07003865 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003866 ALOGV("%s setting device %s on output %d",
3867 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003868 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003869 index = mAudioPatches.indexOfKey(*handle);
3870 if (index >= 0) {
3871 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003872 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003873 }
3874 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003875 patchDesc->setUid(uid);
3876 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003877 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003878 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003879 return INVALID_OPERATION;
3880 }
3881 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3882 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3883 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003884 // only one sink supported when connecting an input device to a mix
3885 if (patch->num_sinks > 1) {
3886 return INVALID_OPERATION;
3887 }
François Gaffie53615e22015-03-19 09:24:12 +01003888 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003889 if (inputDesc == NULL) {
3890 return BAD_VALUE;
3891 }
3892 if (patchDesc != 0) {
3893 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3894 return BAD_VALUE;
3895 }
3896 }
François Gaffie11d30102018-11-02 16:09:09 +01003897 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003898 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003899 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003900 return BAD_VALUE;
3901 }
3902
François Gaffie11d30102018-11-02 16:09:09 +01003903 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003904 patch->sinks[0].sample_rate,
3905 NULL, /*updatedSampleRate*/
3906 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003907 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003908 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003909 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003910 // FIXME for the parameter type,
3911 // and the NONE
3912 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003913 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003914 return INVALID_OPERATION;
3915 }
3916 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003917 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003918 device->toString().c_str(), inputDesc->mIoHandle);
3919 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003920 index = mAudioPatches.indexOfKey(*handle);
3921 if (index >= 0) {
3922 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003923 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003924 }
3925 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003926 patchDesc->setUid(uid);
3927 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003928 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003929 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003930 return INVALID_OPERATION;
3931 }
3932 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3933 // device to device connection
3934 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003935 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003936 return BAD_VALUE;
3937 }
3938 }
François Gaffie11d30102018-11-02 16:09:09 +01003939 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003940 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003941 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003942 return BAD_VALUE;
3943 }
Eric Laurent874c42872014-08-08 15:13:39 -07003944
Eric Laurent6a94d692014-05-20 11:18:06 -07003945 //update source and sink with our own data as the data passed in the patch may
3946 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01003947 PatchBuilder patchBuilder;
3948 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11003949
3950 // if first sink is to MSD, establish single MSD patch
3951 if (getMsdAudioOutDevices().contains(
3952 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
3953 ALOGV("%s patching to MSD", __FUNCTION__);
3954 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
3955 goto installPatch;
3956 }
3957
François Gaffieafd4cea2019-11-18 15:50:22 +01003958 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
3959 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07003960
Eric Laurent874c42872014-08-08 15:13:39 -07003961 for (size_t i = 0; i < patch->num_sinks; i++) {
3962 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003963 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003964 return INVALID_OPERATION;
3965 }
François Gaffie11d30102018-11-02 16:09:09 +01003966 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003967 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003968 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003969 return BAD_VALUE;
3970 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003971 audio_port_config sinkPortConfig = {};
3972 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
3973 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003974
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02003975 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
3976 // volume management purpose (tracking activity)
3977 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
3978 // in config XML to reach the sink so that is can be declared as available.
3979 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3980 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
3981 if (sourceDesc != nullptr) {
3982 // take care of dynamic routing for SwOutput selection,
3983 audio_attributes_t attributes = sourceDesc->attributes();
3984 audio_stream_type_t stream = sourceDesc->stream();
3985 audio_attributes_t resultAttr;
3986 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3987 config.sample_rate = sourceDesc->config().sample_rate;
3988 config.channel_mask = sourceDesc->config().channel_mask;
3989 config.format = sourceDesc->config().format;
3990 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3991 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3992 bool isRequestedDeviceForExclusiveUse = false;
3993 output_type_t outputType;
3994 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
3995 &stream, sourceDesc->uid(), &config, &flags,
3996 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
3997 nullptr, &outputType);
3998 if (output == AUDIO_IO_HANDLE_NONE) {
3999 ALOGV("%s no output for device %s",
4000 __FUNCTION__, sinkDevice->toString().c_str());
4001 return INVALID_OPERATION;
4002 }
4003 outputDesc = mOutputs.valueFor(output);
4004 if (outputDesc->isDuplicated()) {
4005 ALOGE("%s output is duplicated", __func__);
4006 return INVALID_OPERATION;
4007 }
4008 sourceDesc->setSwOutput(outputDesc);
4009 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004010 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004011 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004012 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004013 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01004014 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
4015 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004016 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4017 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004018 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
4019 (sourceDesc != nullptr &&
4020 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004021 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004022 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004023 return INVALID_OPERATION;
4024 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004025 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004026 SortedVector<audio_io_handle_t> outputs =
4027 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4028 // if the sink device is reachable via an opened output stream, request to
4029 // go via this output stream by adding a second source to the patch
4030 // description
4031 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004032 if (output != AUDIO_IO_HANDLE_NONE) {
4033 outputDesc = mOutputs.valueFor(output);
4034 if (outputDesc->isDuplicated()) {
4035 ALOGV("%s output for device %s is duplicated",
4036 __FUNCTION__, sinkDevice->toString().c_str());
4037 return INVALID_OPERATION;
4038 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004039 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004040 }
4041 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004042 audio_port_config srcMixPortConfig = {};
4043 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
François Gaffieafd4cea2019-11-18 15:50:22 +01004044 // for volume control, we may need a valid stream
4045 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
4046 sourceDesc->stream() : AUDIO_STREAM_PATCH;
4047 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004048 }
Eric Laurent83b88082014-06-20 18:31:16 -07004049 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004050 }
4051 // TODO: check from routing capabilities in config file and other conflicting patches
4052
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004053installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004054 status_t status = installPatch(
4055 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004056 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004057 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004058 return INVALID_OPERATION;
4059 }
4060 } else {
4061 return BAD_VALUE;
4062 }
4063 } else {
4064 return BAD_VALUE;
4065 }
4066 return NO_ERROR;
4067}
4068
4069status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4070 uid_t uid)
4071{
4072 ALOGV("releaseAudioPatch() patch %d", handle);
4073
4074 ssize_t index = mAudioPatches.indexOfKey(handle);
4075
4076 if (index < 0) {
4077 return BAD_VALUE;
4078 }
4079 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004080 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4081 __func__, mUidCached, patchDesc->getUid(), uid);
4082 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004083 return INVALID_OPERATION;
4084 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004085 return releaseAudioPatchInternal(handle);
4086}
Eric Laurent6a94d692014-05-20 11:18:06 -07004087
François Gaffieafd4cea2019-11-18 15:50:22 +01004088status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4089 uint32_t delayMs)
4090{
4091 ALOGV("%s patch %d", __func__, handle);
4092 if (mAudioPatches.indexOfKey(handle) < 0) {
4093 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4094 return BAD_VALUE;
4095 }
4096 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004097 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004098 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004099 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004100 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004101 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004102 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004103 return BAD_VALUE;
4104 }
4105
François Gaffie11d30102018-11-02 16:09:09 +01004106 setOutputDevices(outputDesc,
4107 getNewOutputDevices(outputDesc, true /*fromCache*/),
4108 true,
4109 0,
4110 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004111 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4112 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004113 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004114 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004115 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004116 return BAD_VALUE;
4117 }
4118 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004119 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004120 true,
4121 NULL);
4122 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004123 status_t status =
4124 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4125 ALOGV("%s patch panel returned %d patchHandle %d",
4126 __func__, status, patchDesc->getAfHandle());
4127 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004128 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004129 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004130 // SW Bridge
4131 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4132 sp<SwAudioOutputDescriptor> outputDesc =
4133 mOutputs.getOutputFromId(patch->sources[1].id);
4134 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004135 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4136 // releaseOutput has already called closeOuput in case of direct output
4137 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004138 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004139 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4140 // force SwOutput patch removal as AF counter part patch has already gone.
4141 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4142 removeAudioPatch(outputDesc->getPatchHandle());
4143 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004144 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4145 setOutputDevices(outputDesc,
4146 getNewOutputDevices(outputDesc, true /*fromCache*/),
4147 true, /*force*/
4148 0,
4149 NULL);
4150 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004151 } else {
4152 return BAD_VALUE;
4153 }
4154 } else {
4155 return BAD_VALUE;
4156 }
4157 return NO_ERROR;
4158}
4159
4160status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4161 struct audio_patch *patches,
4162 unsigned int *generation)
4163{
François Gaffie53615e22015-03-19 09:24:12 +01004164 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004165 return BAD_VALUE;
4166 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004167 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004168 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004169}
4170
Eric Laurente1715a42014-05-20 11:30:42 -07004171status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004172{
Eric Laurente1715a42014-05-20 11:30:42 -07004173 ALOGV("setAudioPortConfig()");
4174
4175 if (config == NULL) {
4176 return BAD_VALUE;
4177 }
4178 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4179 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004180 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4181 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004182 }
4183
Eric Laurenta121f902014-06-03 13:32:54 -07004184 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004185 if (config->type == AUDIO_PORT_TYPE_MIX) {
4186 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004187 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004188 if (outputDesc == NULL) {
4189 return BAD_VALUE;
4190 }
Eric Laurent84c70242014-06-23 08:46:27 -07004191 ALOG_ASSERT(!outputDesc->isDuplicated(),
4192 "setAudioPortConfig() called on duplicated output %d",
4193 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004194 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004195 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004196 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004197 if (inputDesc == NULL) {
4198 return BAD_VALUE;
4199 }
Eric Laurenta121f902014-06-03 13:32:54 -07004200 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004201 } else {
4202 return BAD_VALUE;
4203 }
4204 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4205 sp<DeviceDescriptor> deviceDesc;
4206 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4207 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4208 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4209 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4210 } else {
4211 return BAD_VALUE;
4212 }
4213 if (deviceDesc == NULL) {
4214 return BAD_VALUE;
4215 }
Eric Laurenta121f902014-06-03 13:32:54 -07004216 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004217 } else {
4218 return BAD_VALUE;
4219 }
4220
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004221 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004222 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4223 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004224 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004225 audioPortConfig->toAudioPortConfig(&newConfig, config);
4226 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004227 }
Eric Laurenta121f902014-06-03 13:32:54 -07004228 if (status != NO_ERROR) {
4229 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004230 }
Eric Laurente1715a42014-05-20 11:30:42 -07004231
4232 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004233}
4234
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004235void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4236{
Eric Laurentd60560a2015-04-10 11:31:20 -07004237 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004238 clearAudioPatches(uid);
4239 clearSessionRoutes(uid);
4240}
4241
Eric Laurent6a94d692014-05-20 11:18:06 -07004242void AudioPolicyManager::clearAudioPatches(uid_t uid)
4243{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004244 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004245 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004246 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004247 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004248 }
4249 }
4250}
4251
François Gaffiec005e562018-11-06 15:04:49 +01004252void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004253{
François Gaffiec005e562018-11-06 15:04:49 +01004254 // Take the first attributes following the product strategy as it is used to retrieve the routed
4255 // device. All attributes wihin a strategy follows the same "routing strategy"
4256 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4257 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004258 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004259 for (size_t j = 0; j < mOutputs.size(); j++) {
4260 if (mOutputs.keyAt(j) == ouptutToSkip) {
4261 continue;
4262 }
4263 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004264 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004265 continue;
4266 }
4267 // If the default device for this strategy is on another output mix,
4268 // invalidate all tracks in this strategy to force re connection.
4269 // Otherwise select new device on the output mix.
4270 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004271 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4272 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004273 }
4274 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004275 setOutputDevices(
4276 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004277 }
4278 }
4279}
4280
4281void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4282{
4283 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004284 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004285 for (size_t i = 0; i < mOutputs.size(); i++) {
4286 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004287 for (const auto& client : outputDesc->getClientIterable()) {
4288 if (client->hasPreferredDevice() && client->uid() == uid) {
4289 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004290 auto clientStrategy = client->strategy();
4291 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4292 end(affectedStrategies)) {
4293 continue;
4294 }
4295 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004296 }
4297 }
4298 }
4299 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004300 for (const auto& strategy : affectedStrategies) {
4301 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004302 }
4303
4304 // remove input routes associated with this uid
4305 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004306 for (size_t i = 0; i < mInputs.size(); i++) {
4307 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004308 for (const auto& client : inputDesc->getClientIterable()) {
4309 if (client->hasPreferredDevice() && client->uid() == uid) {
4310 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4311 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004312 }
4313 }
4314 }
4315 // reroute inputs if necessary
4316 SortedVector<audio_io_handle_t> inputsToClose;
4317 for (size_t i = 0; i < mInputs.size(); i++) {
4318 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004319 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004320 inputsToClose.add(inputDesc->mIoHandle);
4321 }
4322 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004323 for (const auto& input : inputsToClose) {
4324 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004325 }
4326}
4327
Eric Laurentd60560a2015-04-10 11:31:20 -07004328void AudioPolicyManager::clearAudioSources(uid_t uid)
4329{
4330 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004331 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4332 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004333 stopAudioSource(mAudioSources.keyAt(i));
4334 }
4335 }
4336}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004337
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004338status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4339 audio_io_handle_t *ioHandle,
4340 audio_devices_t *device)
4341{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004342 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4343 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004344 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004345 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004346
François Gaffiedf372692015-03-19 10:43:27 +01004347 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004348}
4349
Eric Laurentd60560a2015-04-10 11:31:20 -07004350status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004351 const audio_attributes_t *attributes,
4352 audio_port_handle_t *portId,
4353 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004354{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004355 ALOGV("%s", __FUNCTION__);
4356 *portId = AUDIO_PORT_HANDLE_NONE;
4357
4358 if (source == NULL || attributes == NULL || portId == NULL) {
4359 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4360 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004361 return BAD_VALUE;
4362 }
4363
Eric Laurentd60560a2015-04-10 11:31:20 -07004364 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4365 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004366 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4367 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004368 return INVALID_OPERATION;
4369 }
4370
François Gaffie11d30102018-11-02 16:09:09 +01004371 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004372 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004373 String8(source->ext.device.address),
4374 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004375 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004376 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004377 return BAD_VALUE;
4378 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004379
jiabin4ef93452019-09-10 14:29:54 -07004380 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004381
François Gaffieaaac0fd2018-11-22 17:56:39 +01004382 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004383 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004384 mEngine->getStreamTypeForAttributes(*attributes),
4385 mEngine->getProductStrategyForAttributes(*attributes),
4386 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004387
4388 status_t status = connectAudioSource(sourceDesc);
4389 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004390 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004391 }
4392 return status;
4393}
4394
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004395status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004396{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004397 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004398
4399 // make sure we only have one patch per source.
4400 disconnectAudioSource(sourceDesc);
4401
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004402 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004403 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4404 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4405 sourceDesc->srcDevice()->type(),
4406 String8(sourceDesc->srcDevice()->address().c_str()),
4407 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004408 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004409 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004410 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004411 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004412 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4413 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4414 return INVALID_OPERATION;
4415 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004416 PatchBuilder patchBuilder;
4417 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4418 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4419 status_t status =
4420 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4421 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4422 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4423 return INVALID_OPERATION;
4424 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004425 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004426 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4427 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4428 if (swOutput != 0) {
4429 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004430 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004431 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004432 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004433 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004434 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004435 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004436 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004437 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004438 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004439 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004440 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004441 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4442 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004443 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004444 if (delayMs != 0) {
4445 usleep(delayMs * 1000);
4446 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004447 } else {
4448 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4449 if (hwOutputDesc != 0) {
4450 // create Hwoutput and add to mHwOutputs
4451 } else {
4452 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4453 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004454 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004455 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004456
4457FailureSourceActive:
4458 swOutput->stop();
4459 releaseOutput(sourceDesc->portId());
4460FailureSourceAdded:
4461 sourceDesc->setSwOutput(nullptr);
4462FailureReleasePatch:
4463 releaseAudioPatchInternal(handle);
4464 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004465}
4466
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004467status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004468{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004469 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4470 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004471 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004472 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004473 return BAD_VALUE;
4474 }
4475 status_t status = disconnectAudioSource(sourceDesc);
4476
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004477 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004478 return status;
4479}
4480
Andy Hung2ddee192015-12-18 17:34:44 -08004481status_t AudioPolicyManager::setMasterMono(bool mono)
4482{
4483 if (mMasterMono == mono) {
4484 return NO_ERROR;
4485 }
4486 mMasterMono = mono;
4487 // if enabling mono we close all offloaded devices, which will invalidate the
4488 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4489 // for recreating the new AudioTrack as non-offloaded PCM.
4490 //
4491 // If disabling mono, we leave all tracks as is: we don't know which clients
4492 // and tracks are able to be recreated as offloaded. The next "song" should
4493 // play back offloaded.
4494 if (mMasterMono) {
4495 Vector<audio_io_handle_t> offloaded;
4496 for (size_t i = 0; i < mOutputs.size(); ++i) {
4497 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4498 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4499 offloaded.push(desc->mIoHandle);
4500 }
4501 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004502 for (const auto& handle : offloaded) {
4503 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004504 }
4505 }
4506 // update master mono for all remaining outputs
4507 for (size_t i = 0; i < mOutputs.size(); ++i) {
4508 updateMono(mOutputs.keyAt(i));
4509 }
4510 return NO_ERROR;
4511}
4512
4513status_t AudioPolicyManager::getMasterMono(bool *mono)
4514{
4515 *mono = mMasterMono;
4516 return NO_ERROR;
4517}
4518
Eric Laurentac9cef52017-06-09 15:46:26 -07004519float AudioPolicyManager::getStreamVolumeDB(
4520 audio_stream_type_t stream, int index, audio_devices_t device)
4521{
jiabin9a3361e2019-10-01 09:38:30 -07004522 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004523}
4524
jiabin81772902018-04-02 17:52:27 -07004525status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4526 audio_format_t *surroundFormats,
4527 bool *surroundFormatsEnabled,
4528 bool reported)
4529{
4530 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
4531 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
4532 return BAD_VALUE;
4533 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004534 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
4535 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07004536
4537 size_t formatsWritten = 0;
4538 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004539 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07004540 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004541 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07004542 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08004543 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4544 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
Kriti Dangef6be8f2020-11-05 11:58:19 +01004545 audio_devices_t deviceType = device->type();
4546 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4547 // returns formats reported by HDMI devices.
4548 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4549 continue;
4550 }
4551 // Formats reported by sink devices
4552 std::unordered_set<audio_format_t> formatset;
4553 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4554 formatset.insert(it->second.begin(), it->second.end());
4555 }
4556
4557 // Formats hard-coded in the in policy configuration file (if any).
4558 FormatVector encodedFormats = device->encodedFormats();
4559 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4560 // Filter the formats which are supported by the vendor hardware.
4561 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4562 if (mConfig.getSurroundFormats().count(*it) != 0) {
4563 formats.insert(*it);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004564 } else {
4565 for (const auto& pair : mConfig.getSurroundFormats()) {
Kriti Dangef6be8f2020-11-05 11:58:19 +01004566 if (pair.second.count(*it) != 0) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004567 formats.insert(pair.first);
4568 break;
4569 }
4570 }
4571 }
4572 }
jiabin81772902018-04-02 17:52:27 -07004573 }
4574 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004575 for (const auto& pair : mConfig.getSurroundFormats()) {
4576 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07004577 }
4578 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004579 *numSurroundFormats = formats.size();
4580 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4581 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07004582 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07004583 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07004584 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004585 bool formatEnabled = true;
4586 switch (forceUse) {
4587 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
4588 formatEnabled = mManualSurroundFormats.count(format) != 0;
4589 break;
4590 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4591 formatEnabled = false;
4592 break;
4593 default: // AUTO or ALWAYS => true
4594 break;
jiabin81772902018-04-02 17:52:27 -07004595 }
4596 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4597 }
jiabin81772902018-04-02 17:52:27 -07004598 }
4599 return NO_ERROR;
4600}
4601
4602status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4603{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004604 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004605 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4606 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004607 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004608 return BAD_VALUE;
4609 }
4610
Mikhail Naganov100f0122018-11-29 11:22:16 -08004611 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4612 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004613 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004614 return INVALID_OPERATION;
4615 }
4616
Mikhail Naganov100f0122018-11-29 11:22:16 -08004617 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004618 return NO_ERROR;
4619 }
4620
Mikhail Naganov100f0122018-11-29 11:22:16 -08004621 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004622 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004623 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004624 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004625 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004626 }
4627 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004628 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004629 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004630 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004631 }
4632 }
4633
4634 sp<SwAudioOutputDescriptor> outputDesc;
4635 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004636 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4637 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004638 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4639 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004640 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004641 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004642 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4643 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4644 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004645 name.c_str(),
4646 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004647 if (status != NO_ERROR) {
4648 continue;
4649 }
4650 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4651 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4652 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004653 name.c_str(),
4654 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004655 profileUpdated |= (status == NO_ERROR);
4656 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004657 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004658 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004659 AUDIO_DEVICE_IN_HDMI);
4660 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4661 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004662 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004663 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004664 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4665 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4666 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004667 name.c_str(),
4668 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004669 if (status != NO_ERROR) {
4670 continue;
4671 }
4672 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4673 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4674 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004675 name.c_str(),
4676 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004677 profileUpdated |= (status == NO_ERROR);
4678 }
4679
jiabin81772902018-04-02 17:52:27 -07004680 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004681 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004682 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004683 }
4684
4685 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4686}
4687
Eric Laurent5ada82e2019-08-29 17:53:54 -07004688void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004689{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004690 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004691 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004692 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004693 }
4694}
4695
jiabin6012f912018-11-02 17:06:30 -07004696bool AudioPolicyManager::isHapticPlaybackSupported()
4697{
4698 for (const auto& hwModule : mHwModules) {
4699 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4700 for (const auto &outProfile : outputProfiles) {
4701 struct audio_port audioPort;
4702 outProfile->toAudioPort(&audioPort);
4703 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4704 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4705 return true;
4706 }
4707 }
4708 }
4709 }
4710 return false;
4711}
4712
Eric Laurent8340e672019-11-06 11:01:08 -08004713bool AudioPolicyManager::isCallScreenModeSupported()
4714{
4715 return getConfig().isCallScreenModeSupported();
4716}
4717
4718
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004719status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004720{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004721 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004722 if (!sourceDesc->isConnected()) {
4723 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
4724 return NO_ERROR;
4725 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004726 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4727 if (swOutput != 0) {
4728 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004729 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004730 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004731 }
jiabinbce0c1d2020-10-05 11:20:18 -07004732 if (releaseOutput(sourceDesc->portId())) {
4733 // The output descriptor is reopened to query dynamic profiles. In that case, there is
4734 // no need to release audio patch here but just return NO_ERROR.
4735 return NO_ERROR;
4736 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004737 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004738 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004739 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004740 // close Hwoutput and remove from mHwOutputs
4741 } else {
4742 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4743 }
4744 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004745 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
4746 sourceDesc->disconnect();
4747 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07004748}
4749
François Gaffiec005e562018-11-06 15:04:49 +01004750sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4751 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004752{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004753 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004754 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004755 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004756 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004757 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4758 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004759 source = sourceDesc;
4760 break;
4761 }
4762 }
4763 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004764}
4765
Eric Laurente552edb2014-03-10 17:42:56 -07004766// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004767// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004768// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004769uint32_t AudioPolicyManager::nextAudioPortGeneration()
4770{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004771 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004772}
4773
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004774static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07004775 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
4776 !audioPolicyXmlConfigFile.empty()) {
4777 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
4778 if (ret == NO_ERROR) {
4779 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08004780 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004781 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07004782 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004783 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004784}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004785
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004786AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4787 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004788 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004789 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004790 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004791 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004792 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004793 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004794 mAudioPortGeneration(1),
4795 mBeaconMuteRefCount(0),
4796 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004797 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004798 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004799 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004800 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004801{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004802}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004803
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004804AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4805 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4806{
4807 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004808}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004809
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004810void AudioPolicyManager::loadConfig() {
4811 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004812 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004813 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004814 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004815}
4816
4817status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07004818 {
4819 auto engLib = EngineLibrary::load(
4820 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
4821 if (!engLib) {
4822 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
4823 return NO_INIT;
4824 }
4825 mEngine = engLib->createEngine();
4826 if (mEngine == nullptr) {
4827 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
4828 return NO_INIT;
4829 }
François Gaffie2110e042015-03-24 08:41:51 +01004830 }
4831 mEngine->setObserver(this);
4832 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004833 if (status != NO_ERROR) {
4834 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4835 return status;
4836 }
François Gaffie2110e042015-03-24 08:41:51 +01004837
Eric Laurent1d69c872021-01-11 18:53:01 +01004838 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
4839 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
4840
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004841 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07004842 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004843 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01004844
Eric Laurent3a4311c2014-03-17 12:00:47 -07004845 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004846 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4847 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4848 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004849 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004850 }
jiabin9ff780e2018-03-19 18:19:52 -07004851 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07004852 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07004853 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004854 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004855 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004856 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004857 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004858 }
4859 }
4860 }
Eric Laurente552edb2014-03-10 17:42:56 -07004861
Francois Gaffiebce7cd42020-10-14 16:13:20 +02004862 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07004863
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004864 // Silence ALOGV statements
4865 property_set("log.tag." LOG_TAG, "D");
4866
Eric Laurente552edb2014-03-10 17:42:56 -07004867 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004868 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004869}
4870
Eric Laurente0720872014-03-11 09:30:41 -07004871AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004872{
Eric Laurente552edb2014-03-10 17:42:56 -07004873 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004874 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004875 }
4876 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004877 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004878 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004879 mAvailableOutputDevices.clear();
4880 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004881 mOutputs.clear();
4882 mInputs.clear();
4883 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004884 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004885 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004886}
4887
Eric Laurente0720872014-03-11 09:30:41 -07004888status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004889{
Eric Laurent87ffa392015-05-22 10:32:38 -07004890 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004891}
4892
Eric Laurente552edb2014-03-10 17:42:56 -07004893// ---
4894
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004895void AudioPolicyManager::onNewAudioModulesAvailable()
4896{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004897 DeviceVector newDevices;
4898 onNewAudioModulesAvailableInt(&newDevices);
4899 if (!newDevices.empty()) {
4900 nextAudioPortGeneration();
4901 mpClientInterface->onAudioPortListUpdate();
4902 }
4903}
4904
4905void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
4906{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004907 for (const auto& hwModule : mHwModulesAll) {
4908 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
4909 continue;
4910 }
4911 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
4912 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4913 ALOGW("could not open HW module %s", hwModule->getName());
4914 continue;
4915 }
4916 mHwModules.push_back(hwModule);
4917 // open all output streams needed to access attached devices
4918 // except for direct output streams that are only opened when they are actually
4919 // required by an app.
4920 // This also validates mAvailableOutputDevices list
4921 for (const auto& outProfile : hwModule->getOutputProfiles()) {
4922 if (!outProfile->canOpenNewIo()) {
4923 ALOGE("Invalid Output profile max open count %u for profile %s",
4924 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4925 continue;
4926 }
4927 if (!outProfile->hasSupportedDevices()) {
4928 ALOGW("Output profile contains no device on module %s", hwModule->getName());
4929 continue;
4930 }
4931 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
4932 mTtsOutputAvailable = true;
4933 }
4934
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004935 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4936 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
4937 sp<DeviceDescriptor> supportedDevice = 0;
4938 if (supportedDevices.contains(mDefaultOutputDevice)) {
4939 supportedDevice = mDefaultOutputDevice;
4940 } else {
4941 // choose first device present in profile's SupportedDevices also part of
4942 // mAvailableOutputDevices.
4943 if (availProfileDevices.isEmpty()) {
4944 continue;
4945 }
4946 supportedDevice = availProfileDevices.itemAt(0);
4947 }
4948 if (!mOutputDevicesAll.contains(supportedDevice)) {
4949 continue;
4950 }
4951 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4952 mpClientInterface);
4953 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4954 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4955 AUDIO_STREAM_DEFAULT,
4956 AUDIO_OUTPUT_FLAG_NONE, &output);
4957 if (status != NO_ERROR) {
4958 ALOGW("Cannot open output stream for devices %s on hw module %s",
4959 supportedDevice->toString().c_str(), hwModule->getName());
4960 continue;
4961 }
4962 for (const auto &device : availProfileDevices) {
4963 // give a valid ID to an attached device once confirmed it is reachable
4964 if (!device->isAttached()) {
4965 device->attach(hwModule);
4966 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07004967 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004968 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004969 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4970 }
4971 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02004972 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004973 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4974 mPrimaryOutput = outputDesc;
4975 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004976 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
4977 outputDesc->close();
4978 } else {
4979 addOutput(output, outputDesc);
4980 setOutputDevices(outputDesc,
4981 DeviceVector(supportedDevice),
4982 true,
4983 0,
4984 NULL);
4985 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004986 }
4987 // open input streams needed to access attached devices to validate
4988 // mAvailableInputDevices list
4989 for (const auto& inProfile : hwModule->getInputProfiles()) {
4990 if (!inProfile->canOpenNewIo()) {
4991 ALOGE("Invalid Input profile max open count %u for profile %s",
4992 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4993 continue;
4994 }
4995 if (!inProfile->hasSupportedDevices()) {
4996 ALOGW("Input profile contains no device on module %s", hwModule->getName());
4997 continue;
4998 }
4999 // chose first device present in profile's SupportedDevices also part of
5000 // available input devices
5001 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5002 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5003 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005004 ALOGV("%s: Input device list is empty! for profile %s",
5005 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005006 continue;
5007 }
5008 sp<AudioInputDescriptor> inputDesc =
5009 new AudioInputDescriptor(inProfile, mpClientInterface);
5010
5011 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5012 status_t status = inputDesc->open(nullptr,
5013 availProfileDevices.itemAt(0),
5014 AUDIO_SOURCE_MIC,
5015 AUDIO_INPUT_FLAG_NONE,
5016 &input);
5017 if (status != NO_ERROR) {
5018 ALOGW("Cannot open input stream for device %s on hw module %s",
5019 availProfileDevices.toString().c_str(),
5020 hwModule->getName());
5021 continue;
5022 }
5023 for (const auto &device : availProfileDevices) {
5024 // give a valid ID to an attached device once confirmed it is reachable
5025 if (!device->isAttached()) {
5026 device->attach(hwModule);
5027 device->importAudioPortAndPickAudioProfile(inProfile, true);
5028 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005029 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005030 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5031 }
5032 }
5033 inputDesc->close();
5034 }
5035 }
5036}
5037
Eric Laurent98e38192018-02-15 18:31:53 -08005038void AudioPolicyManager::addOutput(audio_io_handle_t output,
5039 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005040{
Eric Laurent1c333e22014-05-20 10:48:17 -07005041 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005042 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005043 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005044 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005045 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005046}
5047
François Gaffie53615e22015-03-19 09:24:12 +01005048void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5049{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005050 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5051 ALOGV("%s: removing primary output", __func__);
5052 mPrimaryOutput = nullptr;
5053 }
François Gaffie53615e22015-03-19 09:24:12 +01005054 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005055 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005056}
5057
Eric Laurent98e38192018-02-15 18:31:53 -08005058void AudioPolicyManager::addInput(audio_io_handle_t input,
5059 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005060{
Eric Laurent1c333e22014-05-20 10:48:17 -07005061 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005062 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005063}
Eric Laurente552edb2014-03-10 17:42:56 -07005064
François Gaffie11d30102018-11-02 16:09:09 +01005065status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005066 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005067 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005068{
François Gaffie11d30102018-11-02 16:09:09 +01005069 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005070 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005071 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005072
François Gaffie11d30102018-11-02 16:09:09 +01005073 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005074 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005075 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005076 }
Eric Laurente552edb2014-03-10 17:42:56 -07005077
Eric Laurent3b73df72014-03-11 09:06:29 -07005078 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005079 // first call getAudioPort to get the supported attributes from the HAL
5080 struct audio_port_v7 port = {};
5081 device->toAudioPort(&port);
5082 status_t status = mpClientInterface->getAudioPort(&port);
5083 if (status == NO_ERROR) {
5084 device->importAudioPort(port);
5085 }
5086
5087 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005088 for (size_t i = 0; i < mOutputs.size(); i++) {
5089 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005090 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005091 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005092 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5093 mOutputs.keyAt(i), device->toString().c_str());
5094 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005095 }
5096 }
5097 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005098 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005099 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005100 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5101 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005102 if (profile->supportsDevice(device)) {
5103 profiles.add(profile);
5104 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5105 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005106 }
5107 }
5108 }
5109
Eric Laurent7b279bb2015-12-14 10:18:23 -08005110 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005111
Eric Laurente552edb2014-03-10 17:42:56 -07005112 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005113 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005114 return BAD_VALUE;
5115 }
5116
5117 // open outputs for matching profiles if needed. Direct outputs are also opened to
5118 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5119 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005120 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005121
5122 // nothing to do if one output is already opened for this profile
5123 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005124 for (j = 0; j < outputs.size(); j++) {
5125 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005126 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005127 // matching profile: save the sample rates, format and channel masks supported
5128 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005129 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005130 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005131 }
Eric Laurente552edb2014-03-10 17:42:56 -07005132 break;
5133 }
5134 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005135 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005136 continue;
5137 }
5138
Eric Laurent3974e3b2017-12-07 17:58:43 -08005139 if (!profile->canOpenNewIo()) {
5140 ALOGW("Max Output number %u already opened for this profile %s",
5141 profile->maxOpenCount, profile->getTagName().c_str());
5142 continue;
5143 }
5144
Eric Laurent83efe1c2017-07-09 16:51:08 -07005145 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005146 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005147 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5148 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005149 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005150 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005151 profiles.removeAt(profile_index);
5152 profile_index--;
5153 } else {
5154 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005155 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005156 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005157 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5158 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005159 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005160 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005161
François Gaffie11d30102018-11-02 16:09:09 +01005162 if (device_distinguishes_on_address(deviceType)) {
5163 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5164 device->toString().c_str());
5165 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5166 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005167 }
Eric Laurente552edb2014-03-10 17:42:56 -07005168 ALOGV("checkOutputsForDevice(): adding output %d", output);
5169 }
5170 }
5171
5172 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005173 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005174 return BAD_VALUE;
5175 }
Eric Laurentd4692962014-05-05 18:13:44 -07005176 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005177 // check if one opened output is not needed any more after disconnecting one device
5178 for (size_t i = 0; i < mOutputs.size(); i++) {
5179 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005180 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005181 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005182 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
jiabinbce0c1d2020-10-05 11:20:18 -07005183 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005184 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005185 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005186 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5187 mOutputs.keyAt(i));
5188 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005189 }
Eric Laurente552edb2014-03-10 17:42:56 -07005190 }
5191 }
Eric Laurentd4692962014-05-05 18:13:44 -07005192 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005193 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005194 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5195 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005196 if (!profile->supportsDevice(device)) {
5197 continue;
5198 }
5199 ALOGV("checkOutputsForDevice(): "
5200 "clearing direct output profile %zu on module %s",
5201 j, hwModule->getName());
5202 profile->clearAudioProfiles();
5203 if (!profile->hasDynamicAudioProfile()) {
5204 continue;
5205 }
5206 // When a device is disconnected, if there is an IOProfile that contains dynamic
5207 // profiles and supports the disconnected device, call getAudioPort to repopulate
5208 // the capabilities of the devices that is supported by the IOProfile.
5209 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5210 if (supportedDevice == device ||
5211 !mAvailableOutputDevices.contains(supportedDevice)) {
5212 continue;
5213 }
5214 struct audio_port_v7 port;
5215 supportedDevice->toAudioPort(&port);
5216 status_t status = mpClientInterface->getAudioPort(&port);
5217 if (status == NO_ERROR) {
5218 supportedDevice->importAudioPort(port);
5219 }
Eric Laurente552edb2014-03-10 17:42:56 -07005220 }
5221 }
5222 }
5223 }
5224 return NO_ERROR;
5225}
5226
François Gaffie11d30102018-11-02 16:09:09 +01005227status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005228 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005229{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005230 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005231
François Gaffie11d30102018-11-02 16:09:09 +01005232 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005233 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005234 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005235 }
5236
Eric Laurentd4692962014-05-05 18:13:44 -07005237 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005238 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005239 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005240 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005241 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005242 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005243 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005244 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005245
François Gaffie11d30102018-11-02 16:09:09 +01005246 if (profile->supportsDevice(device)) {
5247 profiles.add(profile);
5248 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5249 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005250 }
5251 }
5252 }
5253
Eric Laurent0dd51852019-04-19 18:18:58 -07005254 if (profiles.isEmpty()) {
5255 ALOGW("%s: No input profile available for device %s",
5256 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005257 return BAD_VALUE;
5258 }
5259
5260 // open inputs for matching profiles if needed. Direct inputs are also opened to
5261 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5262 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5263
Eric Laurent1c333e22014-05-20 10:48:17 -07005264 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005265
Eric Laurentd4692962014-05-05 18:13:44 -07005266 // nothing to do if one input is already opened for this profile
5267 size_t input_index;
5268 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5269 desc = mInputs.valueAt(input_index);
5270 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005271 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005272 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005273 }
Eric Laurentd4692962014-05-05 18:13:44 -07005274 break;
5275 }
5276 }
5277 if (input_index != mInputs.size()) {
5278 continue;
5279 }
5280
Eric Laurent3974e3b2017-12-07 17:58:43 -08005281 if (!profile->canOpenNewIo()) {
5282 ALOGW("Max Input number %u already opened for this profile %s",
5283 profile->maxOpenCount, profile->getTagName().c_str());
5284 continue;
5285 }
5286
Eric Laurentfe231122017-11-17 17:48:06 -08005287 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005288 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005289 status_t status = desc->open(nullptr,
5290 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005291 AUDIO_SOURCE_MIC,
5292 AUDIO_INPUT_FLAG_NONE,
5293 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005294
Eric Laurentcf2c0212014-07-25 16:20:43 -07005295 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005296 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005297 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005298 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005299 mpClientInterface->setParameters(input, String8(param));
5300 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005301 }
François Gaffie11d30102018-11-02 16:09:09 +01005302 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005303 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005304 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005305 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005306 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005307 }
5308
Eric Laurent0dd51852019-04-19 18:18:58 -07005309 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005310 addInput(input, desc);
5311 }
5312 } // endif input != 0
5313
Eric Laurentcf2c0212014-07-25 16:20:43 -07005314 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005315 ALOGW("%s could not open input for device %s", __func__,
5316 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005317 profiles.removeAt(profile_index);
5318 profile_index--;
5319 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005320 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005321 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005322 }
Eric Laurentd4692962014-05-05 18:13:44 -07005323 ALOGV("checkInputsForDevice(): adding input %d", input);
5324 }
5325 } // end scan profiles
5326
5327 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005328 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005329 return BAD_VALUE;
5330 }
5331 } else {
5332 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005333 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005334 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005335 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005336 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005337 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005338 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005339 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005340 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5341 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005342 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005343 }
5344 }
5345 }
5346 } // end disconnect
5347
5348 return NO_ERROR;
5349}
5350
5351
Eric Laurente0720872014-03-11 09:30:41 -07005352void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005353{
5354 ALOGV("closeOutput(%d)", output);
5355
François Gaffie1c878552018-11-22 16:53:21 +01005356 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5357 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005358 ALOGW("closeOutput() unknown output %d", output);
5359 return;
5360 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005361 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005362 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005363
Eric Laurente552edb2014-03-10 17:42:56 -07005364 // look for duplicated outputs connected to the output being removed.
5365 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005366 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5367 if (dupOutput->isDuplicated() &&
5368 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5369 sp<SwAudioOutputDescriptor> remainingOutput =
5370 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005371 // As all active tracks on duplicated output will be deleted,
5372 // and as they were also referenced on the other output, the reference
5373 // count for their stream type must be adjusted accordingly on
5374 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005375 const bool wasActive = remainingOutput->isActive();
5376 // Note: no-op on the closing output where all clients has already been set inactive
5377 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005378 // stop() will be a no op if the output is still active but is needed in case all
5379 // active streams refcounts where cleared above
5380 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005381 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005382 }
Eric Laurente552edb2014-03-10 17:42:56 -07005383 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5384 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5385
5386 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005387 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005388 }
5389 }
5390
Eric Laurent05b90f82014-08-27 15:32:29 -07005391 nextAudioPortGeneration();
5392
François Gaffie1c878552018-11-22 16:53:21 +01005393 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005394 if (index >= 0) {
5395 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005396 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5397 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005398 mAudioPatches.removeItemsAt(index);
5399 mpClientInterface->onAudioPatchListUpdate();
5400 }
5401
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005402 if (closingOutputWasActive) {
5403 closingOutput->stop();
5404 }
François Gaffie1c878552018-11-22 16:53:21 +01005405 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005406
François Gaffie53615e22015-03-19 09:24:12 +01005407 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005408 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005409
5410 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5411 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005412 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005413 bool directOutputOpen = false;
5414 for (size_t i = 0; i < mOutputs.size(); i++) {
5415 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5416 directOutputOpen = true;
5417 break;
5418 }
5419 }
5420 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11005421 ALOGV("no direct outputs open, reset MSD patches");
5422 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5423 // how output devices for patching are resolved. Avoid by caching and reusing the
5424 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5425 // devices to patch to. This may be complicated by the fact that devices may become
5426 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005427 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005428 }
5429 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005430}
5431
5432void AudioPolicyManager::closeInput(audio_io_handle_t input)
5433{
5434 ALOGV("closeInput(%d)", input);
5435
5436 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5437 if (inputDesc == NULL) {
5438 ALOGW("closeInput() unknown input %d", input);
5439 return;
5440 }
5441
Eric Laurent6a94d692014-05-20 11:18:06 -07005442 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005443
François Gaffie11d30102018-11-02 16:09:09 +01005444 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005445 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005446 if (index >= 0) {
5447 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005448 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5449 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005450 mAudioPatches.removeItemsAt(index);
5451 mpClientInterface->onAudioPatchListUpdate();
5452 }
5453
Eric Laurentfe231122017-11-17 17:48:06 -08005454 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005455 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005456
François Gaffie11d30102018-11-02 16:09:09 +01005457 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5458 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005459 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005460 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005461 }
Eric Laurente552edb2014-03-10 17:42:56 -07005462}
5463
François Gaffie11d30102018-11-02 16:09:09 +01005464SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5465 const DeviceVector &devices,
5466 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005467{
5468 SortedVector<audio_io_handle_t> outputs;
5469
François Gaffie11d30102018-11-02 16:09:09 +01005470 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005471 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005472 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005473 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005474 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005475 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005476 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005477 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005478 outputs.add(openOutputs.keyAt(i));
5479 }
5480 }
5481 return outputs;
5482}
5483
Mikhail Naganov37977152018-07-11 15:54:44 -07005484void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5485{
5486 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5487 // output is suspended before any tracks are moved to it
5488 checkA2dpSuspend();
5489 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005490 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005491 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005492 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005493 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11005494 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
5495 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
5496 // configuration changes will ultimately be rerouted correctly. We can still avoid
5497 // unnecessary rerouting by caching and reusing the arguments to
5498 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
5499 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005500 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005501 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07005502 // an event that changed routing likely occurred, inform upper layers
5503 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07005504}
5505
François Gaffiec005e562018-11-06 15:04:49 +01005506bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5507 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005508{
François Gaffiec005e562018-11-06 15:04:49 +01005509 return mEngine->getProductStrategyForAttributes(lAttr) ==
5510 mEngine->getProductStrategyForAttributes(rAttr);
5511}
5512
Francois Gaffieff1eb522020-05-06 18:37:04 +02005513void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
5514{
5515 for (size_t i = 0; i < mAudioSources.size(); i++) {
5516 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5517 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005518 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
5519 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02005520 connectAudioSource(sourceDesc);
5521 }
5522 }
5523}
5524
5525void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
5526{
5527 for (size_t i = 0; i < mAudioSources.size(); i++) {
5528 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5529 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
5530 && sourceDesc->swOutput().promote()->mIoHandle == output) {
5531 disconnectAudioSource(sourceDesc);
5532 }
5533 }
5534}
5535
François Gaffiec005e562018-11-06 15:04:49 +01005536void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5537{
5538 auto psId = mEngine->getProductStrategyForAttributes(attr);
5539
5540 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5541 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005542
François Gaffie11d30102018-11-02 16:09:09 +01005543 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5544 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005545
Eric Laurentc209fe42020-06-05 18:11:23 -07005546 uint32_t maxLatency = 0;
5547 bool invalidate = false;
5548 // take into account dynamic audio policies related changes: if a client is now associated
5549 // to a different policy mix than at creation time, invalidate corresponding stream
5550 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5551 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5552 if (desc->isDuplicated()) {
5553 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005554 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005555 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5556 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5557 continue;
5558 }
5559 sp<AudioPolicyMix> primaryMix;
5560 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5561 client->flags(), primaryMix, nullptr);
5562 if (status != OK) {
5563 continue;
5564 }
yucliuf4de36d2020-09-14 14:57:56 -07005565 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005566 invalidate = true;
5567 if (desc->isStrategyActive(psId)) {
5568 maxLatency = desc->latency();
5569 }
5570 break;
5571 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005572 }
5573 }
5574
Eric Laurentc209fe42020-06-05 18:11:23 -07005575 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005576 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5577 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005578 for (audio_io_handle_t srcOut : srcOutputs) {
5579 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005580 if (desc == nullptr) continue;
5581
5582 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005583 maxLatency = desc->latency();
5584 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005585
5586 if (invalidate) continue;
5587
5588 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005589 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005590 // a client on a non direct outputs has necessarily a linear PCM format
5591 // so we can call selectOutput() safely
5592 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5593 client->flags(),
5594 client->config().format,
5595 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07005596 client->config().sample_rate,
5597 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07005598 if (newOutput != srcOut) {
5599 invalidate = true;
5600 break;
5601 }
5602 } else {
5603 sp<IOProfile> profile = getProfileForOutput(newDevices,
5604 client->config().sample_rate,
5605 client->config().format,
5606 client->config().channel_mask,
5607 client->flags(),
5608 true /* directOnly */);
5609 if (profile != desc->mProfile) {
5610 invalidate = true;
5611 break;
5612 }
5613 }
5614 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005615 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005616
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005617 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005618 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005619 std::to_string(srcOutputs[0]).c_str(),
5620 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005621 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005622 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005623 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005624 if (desc == nullptr) continue;
5625
5626 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005627 setStrategyMute(psId, true, desc);
5628 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005629 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005630 }
François Gaffiec005e562018-11-06 15:04:49 +01005631 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005632 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005633 connectAudioSource(source);
5634 }
Eric Laurente552edb2014-03-10 17:42:56 -07005635 }
5636
François Gaffiec005e562018-11-06 15:04:49 +01005637 // Move effects associated to this stream from previous output to new output
5638 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005639 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005640 }
François Gaffiec005e562018-11-06 15:04:49 +01005641 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005642 if (invalidate) {
5643 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5644 mpClientInterface->invalidateStream(stream);
5645 }
Eric Laurente552edb2014-03-10 17:42:56 -07005646 }
5647 }
5648}
5649
Eric Laurente0720872014-03-11 09:30:41 -07005650void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005651{
François Gaffiec005e562018-11-06 15:04:49 +01005652 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5653 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5654 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02005655 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01005656 }
Eric Laurente552edb2014-03-10 17:42:56 -07005657}
5658
Kevin Rocard153f92d2018-12-18 18:33:28 -08005659void AudioPolicyManager::checkSecondaryOutputs() {
5660 std::set<audio_stream_type_t> streamsToInvalidate;
5661 for (size_t i = 0; i < mOutputs.size(); i++) {
5662 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5663 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005664 sp<AudioPolicyMix> primaryMix;
5665 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07005666 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07005667 client->flags(), primaryMix, &secondaryMixes);
5668 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5669 for (auto &secondaryMix : secondaryMixes) {
5670 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5671 if (outputDesc != nullptr &&
5672 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5673 secondaryDescs.push_back(outputDesc);
5674 }
5675 }
5676
Kevin Rocard94114a22019-04-01 19:38:23 -07005677 if (status != OK ||
5678 !std::equal(client->getSecondaryOutputs().begin(),
Kevin Rocard153f92d2018-12-18 18:33:28 -08005679 client->getSecondaryOutputs().end(),
5680 secondaryDescs.begin(), secondaryDescs.end())) {
5681 streamsToInvalidate.insert(client->stream());
5682 }
5683 }
5684 }
5685 for (audio_stream_type_t stream : streamsToInvalidate) {
5686 ALOGD("%s Invalidate stream %d due to secondary output change", __func__, stream);
5687 mpClientInterface->invalidateStream(stream);
5688 }
5689}
5690
Eric Laurent2517af32020-11-25 15:31:27 +01005691bool AudioPolicyManager::isScoRequestedForComm() const {
5692 AudioDeviceTypeAddrVector devices;
5693 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
5694 for (const auto &device : devices) {
5695 if (audio_is_bluetooth_out_sco_device(device.mType)) {
5696 return true;
5697 }
5698 }
5699 return false;
5700}
5701
Eric Laurente0720872014-03-11 09:30:41 -07005702void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005703{
François Gaffie53615e22015-03-19 09:24:12 +01005704 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005705 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005706 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005707 return;
5708 }
5709
Eric Laurent3a4311c2014-03-17 12:00:47 -07005710 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07005711 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
5712 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01005713 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07005714
5715 // if suspended, restore A2DP output if:
5716 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01005717 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07005718 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005719 //
Eric Laurentf732e072016-08-03 19:30:28 -07005720 // if not suspended, suspend A2DP output if:
5721 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01005722 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07005723 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005724 //
5725 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005726 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01005727 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07005728 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005729 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005730
5731 mpClientInterface->restoreOutput(a2dpOutput);
5732 mA2dpSuspended = false;
5733 }
5734 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005735 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01005736 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07005737 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005738 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005739
5740 mpClientInterface->suspendOutput(a2dpOutput);
5741 mA2dpSuspended = true;
5742 }
5743 }
5744}
5745
François Gaffie11d30102018-11-02 16:09:09 +01005746DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5747 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005748{
François Gaffie11d30102018-11-02 16:09:09 +01005749 DeviceVector devices;
5750
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005751 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005752 if (index >= 0) {
5753 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005754 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005755 ALOGV("%s device %s forced by patch %d", __func__,
5756 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5757 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005758 }
5759 }
5760
Dean Wheatley514b4312020-06-17 21:45:00 +10005761 // Do not retrieve engine device for outputs through MSD
5762 // TODO: support explicit routing requests by resetting MSD patch to engine device.
5763 if (outputDesc->devices() == getMsdAudioOutDevices()) {
5764 return outputDesc->devices();
5765 }
5766
Eric Laurent97ac8712018-07-27 18:59:02 -07005767 // Honor explicit routing requests only if no client using default routing is active on this
5768 // input: a specific app can not force routing for other apps by setting a preferred device.
5769 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005770 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005771 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005772 if (device != nullptr) {
5773 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07005774 }
5775
François Gaffiea807ef92018-11-05 10:44:33 +01005776 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5777 // of setForceUse / Default Bus device here
5778 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5779 if (device != nullptr) {
5780 return DeviceVector(device);
5781 }
5782
François Gaffiec005e562018-11-06 15:04:49 +01005783 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5784 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5785 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305786 auto hasStreamActive = [&](auto stream) {
5787 return hasStream(streams, stream) && isStreamActive(stream, 0);
5788 };
Eric Laurent484e9272018-06-07 17:29:23 -07005789
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305790 auto doGetOutputDevicesForVoice = [&]() {
5791 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
5792 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL))) &&
5793 (isInCall() ||
5794 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc));
5795 };
5796
5797 // With low-latency playing on speaker, music on WFD, when the first low-latency
5798 // output is stopped, getNewOutputDevices checks for a product strategy
5799 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
5800 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
5801 // devices are returned for STRATEGY_SONIFICATION without checking whether the
5802 // stream is associated to the output descriptor.
5803 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
5804 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
5805 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
5806 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01005807 // Retrieval of devices for voice DL is done on primary output profile, cannot
5808 // check the route (would force modifying configuration file for this profile)
5809 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5810 break;
5811 }
Eric Laurente552edb2014-03-10 17:42:56 -07005812 }
François Gaffiec005e562018-11-06 15:04:49 +01005813 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01005814 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005815}
5816
François Gaffie11d30102018-11-02 16:09:09 +01005817sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5818 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005819{
François Gaffie11d30102018-11-02 16:09:09 +01005820 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005821
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005822 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005823 if (index >= 0) {
5824 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005825 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005826 ALOGV("getNewInputDevice() device %s forced by patch %d",
5827 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5828 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005829 }
5830 }
5831
Eric Laurent97ac8712018-07-27 18:59:02 -07005832 // Honor explicit routing requests only if no client using default routing is active on this
5833 // input: a specific app can not force routing for other apps by setting a preferred device.
5834 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005835 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5836 if (device != nullptr) {
5837 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005838 }
5839
Eric Laurentdc95a252018-04-12 12:46:56 -07005840 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005841 // a null sp<>, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01005842 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5843 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5844 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005845 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005846 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
François Gaffiec005e562018-11-06 15:04:49 +01005847 device = mEngine->getInputDeviceForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005848 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005849
Eric Laurente552edb2014-03-10 17:42:56 -07005850 return device;
5851}
5852
Eric Laurent794fde22016-03-11 09:50:45 -08005853bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5854 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005855 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005856}
5857
Eric Laurente0720872014-03-11 09:30:41 -07005858audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005859 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005860 // getOutputDevicesForStream's behavior for invalid streams.
5861 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5862 // device for music stream), but we want to return the empty set.
5863 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005864 return AUDIO_DEVICE_NONE;
5865 }
François Gaffie11d30102018-11-02 16:09:09 +01005866 DeviceVector activeDevices;
5867 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00005868 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
5869 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01005870 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005871 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005872 }
François Gaffiec005e562018-11-06 15:04:49 +01005873 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005874 devices.merge(curDevices);
5875 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005876 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07005877 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01005878 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005879 }
5880 }
Eric Laurente552edb2014-03-10 17:42:56 -07005881 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005882
Eric Laurentb0688d62018-08-14 15:49:18 -07005883 // Favor devices selected on active streams if any to report correct device in case of
5884 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005885 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005886 devices = activeDevices;
5887 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005888 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5889 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07005890 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01005891 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07005892 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01005893 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005894 }
jiabin9a3361e2019-10-01 09:38:30 -07005895 // FIXME: use DeviceTypeSet when Java layer is ready for it.
5896 return deviceTypesToBitMask(devices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005897}
5898
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005899status_t AudioPolicyManager::getDevicesForAttributes(
5900 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
5901 if (devices == nullptr) {
5902 return BAD_VALUE;
5903 }
5904 // check dynamic policies but only for primary descriptors (secondary not used for audible
5905 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07005906 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005907 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07005908 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005909 if (status != OK) {
5910 return status;
5911 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005912 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
5913 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
5914 devices->push_back(device);
5915 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005916 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005917 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5918 for (const auto& device : curDevices) {
5919 devices->push_back(device->getDeviceTypeAddr());
5920 }
5921 return NO_ERROR;
5922}
5923
Eric Laurente0720872014-03-11 09:30:41 -07005924void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005925 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005926 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01005927 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005928 updateDevicesAndOutputs();
5929 break;
5930 default:
5931 break;
5932 }
5933}
5934
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005935uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005936
5937 // skip beacon mute management if a dedicated TTS output is available
5938 if (mTtsOutputAvailable) {
5939 return 0;
5940 }
5941
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005942 switch(event) {
5943 case STARTING_OUTPUT:
5944 mBeaconMuteRefCount++;
5945 break;
5946 case STOPPING_OUTPUT:
5947 if (mBeaconMuteRefCount > 0) {
5948 mBeaconMuteRefCount--;
5949 }
5950 break;
5951 case STARTING_BEACON:
5952 mBeaconPlayingRefCount++;
5953 break;
5954 case STOPPING_BEACON:
5955 if (mBeaconPlayingRefCount > 0) {
5956 mBeaconPlayingRefCount--;
5957 }
5958 break;
5959 }
5960
5961 if (mBeaconMuteRefCount > 0) {
5962 // any playback causes beacon to be muted
5963 return setBeaconMute(true);
5964 } else {
5965 // no other playback: unmute when beacon starts playing, mute when it stops
5966 return setBeaconMute(mBeaconPlayingRefCount == 0);
5967 }
5968}
5969
5970uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5971 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5972 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5973 // keep track of muted state to avoid repeating mute/unmute operations
5974 if (mBeaconMuted != mute) {
5975 // mute/unmute AUDIO_STREAM_TTS on all outputs
5976 ALOGV("\t muting %d", mute);
5977 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01005978 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005979 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005980 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07005981 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005982 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07005983 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005984 maxLatency = latency;
5985 }
5986 }
5987 mBeaconMuted = mute;
5988 return maxLatency;
5989 }
5990 return 0;
5991}
5992
Eric Laurente0720872014-03-11 09:30:41 -07005993void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005994{
François Gaffiec005e562018-11-06 15:04:49 +01005995 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07005996 mPreviousOutputs = mOutputs;
5997}
5998
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005999uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006000 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006001 uint32_t delayMs)
6002{
6003 // mute/unmute strategies using an incompatible device combination
6004 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6005 // if unmuting, unmute only after the specified delay
6006 if (outputDesc->isDuplicated()) {
6007 return 0;
6008 }
6009
6010 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006011 DeviceVector devices = outputDesc->devices();
6012 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006013
François Gaffiec005e562018-11-06 15:04:49 +01006014 auto productStrategies = mEngine->getOrderedProductStrategies();
6015 for (const auto &productStrategy : productStrategies) {
6016 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6017 DeviceVector curDevices =
6018 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6019 curDevices = curDevices.filter(outputDesc->supportedDevices());
6020 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006021 bool doMute = false;
6022
François Gaffiec005e562018-11-06 15:04:49 +01006023 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006024 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006025 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6026 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006027 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006028 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006029 }
Eric Laurent99401132014-05-07 19:48:15 -07006030 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006031 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006032 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006033 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006034 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006035 continue;
6036 }
François Gaffiec005e562018-11-06 15:04:49 +01006037 ALOGVV("%s() %s (curDevice %s)", __func__,
6038 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6039 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6040 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006041 if (mute) {
6042 // FIXME: should not need to double latency if volume could be applied
6043 // immediately by the audioflinger mixer. We must account for the delay
6044 // between now and the next time the audioflinger thread for this output
6045 // will process a buffer (which corresponds to one buffer size,
6046 // usually 1/2 or 1/4 of the latency).
6047 if (muteWaitMs < desc->latency() * 2) {
6048 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006049 }
6050 }
6051 }
6052 }
6053 }
6054 }
6055
Eric Laurent99401132014-05-07 19:48:15 -07006056 // temporary mute output if device selection changes to avoid volume bursts due to
6057 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006058 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006059 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
6060 // temporary mute duration is conservatively set to 4 times the reported latency
6061 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
6062 if (muteWaitMs < tempMuteWaitMs) {
6063 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006064 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006065 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6066 // make sure that we do not start the temporary mute period too early in case of
6067 // delayed device change
6068 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6069 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006070 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006071 }
6072 }
6073
Eric Laurente552edb2014-03-10 17:42:56 -07006074 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6075 if (muteWaitMs > delayMs) {
6076 muteWaitMs -= delayMs;
6077 usleep(muteWaitMs * 1000);
6078 return muteWaitMs;
6079 }
6080 return 0;
6081}
6082
François Gaffie11d30102018-11-02 16:09:09 +01006083uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6084 const DeviceVector &devices,
6085 bool force,
6086 int delayMs,
6087 audio_patch_handle_t *patchHandle,
6088 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006089{
François Gaffie11d30102018-11-02 16:09:09 +01006090 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006091 uint32_t muteWaitMs;
6092
6093 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006094 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6095 nullptr /* patchHandle */, requiresMuteCheck);
6096 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6097 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006098 return muteWaitMs;
6099 }
Eric Laurente552edb2014-03-10 17:42:56 -07006100
6101 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006102 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006103 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07006104
François Gaffie11d30102018-11-02 16:09:09 +01006105 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6106
6107 if (!filteredDevices.isEmpty()) {
6108 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006109 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006110
6111 // if the outputs are not materially active, there is no need to mute.
6112 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006113 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006114 } else {
6115 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6116 muteWaitMs = 0;
6117 }
Eric Laurente552edb2014-03-10 17:42:56 -07006118
Eric Laurent79ea9582020-06-11 18:49:24 -07006119 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6120 // output profile or if new device is not supported AND previous device(s) is(are) still
6121 // available (otherwise reset device must be done on the output)
6122 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
6123 !mAvailableOutputDevices.filter(prevDevices).empty()) {
6124 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6125 // restore previous device after evaluating strategy mute state
6126 outputDesc->setDevices(prevDevices);
6127 return muteWaitMs;
6128 }
6129
Eric Laurente552edb2014-03-10 17:42:56 -07006130 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006131 // the requested device is AUDIO_DEVICE_NONE
6132 // OR the requested device is the same as current device
6133 // AND force is not specified
6134 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006135 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006136 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01006137 !force && outputDesc->getPatchHandle() != 0) {
6138 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6139 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07006140 return muteWaitMs;
6141 }
6142
François Gaffie11d30102018-11-02 16:09:09 +01006143 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006144
Eric Laurente552edb2014-03-10 17:42:56 -07006145 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01006146 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006147 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006148 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006149 PatchBuilder patchBuilder;
6150 patchBuilder.addSource(outputDesc);
6151 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6152 for (const auto &filteredDevice : filteredDevices) {
6153 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006154 }
6155
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006156 // Add half reported latency to delayMs when muteWaitMs is null in order
6157 // to avoid disordered sequence of muting volume and changing devices.
6158 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6159 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006160 }
Eric Laurente552edb2014-03-10 17:42:56 -07006161
6162 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006163 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006164
6165 return muteWaitMs;
6166}
6167
Eric Laurentc75307b2015-03-17 15:29:32 -07006168status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006169 int delayMs,
6170 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006171{
Eric Laurent6a94d692014-05-20 11:18:06 -07006172 ssize_t index;
6173 if (patchHandle) {
6174 index = mAudioPatches.indexOfKey(*patchHandle);
6175 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006176 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006177 }
6178 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006179 return INVALID_OPERATION;
6180 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006181 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006182 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006183 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006184 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006185 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006186 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006187 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006188 return status;
6189}
6190
6191status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006192 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006193 bool force,
6194 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006195{
6196 status_t status = NO_ERROR;
6197
Eric Laurent1f2f2232014-06-02 12:01:23 -07006198 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006199 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6200 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006201
François Gaffie11d30102018-11-02 16:09:09 +01006202 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006203 PatchBuilder patchBuilder;
6204 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006205 // AUDIO_SOURCE_HOTWORD is for internal use only:
6206 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006207 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6208 auto result = usecase;
6209 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6210 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6211 }
6212 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006213 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006214 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006215 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006216 }
6217 }
6218 return status;
6219}
6220
Eric Laurent6a94d692014-05-20 11:18:06 -07006221status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6222 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006223{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006224 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006225 ssize_t index;
6226 if (patchHandle) {
6227 index = mAudioPatches.indexOfKey(*patchHandle);
6228 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006229 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006230 }
6231 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006232 return INVALID_OPERATION;
6233 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006234 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006235 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006236 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006237 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006238 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006239 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006240 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006241 return status;
6242}
6243
François Gaffie11d30102018-11-02 16:09:09 +01006244sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006245 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006246 audio_format_t& format,
6247 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006248 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006249{
6250 // Choose an input profile based on the requested capture parameters: select the first available
6251 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006252 //
6253 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6254 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006255
Glenn Kasten730b9262018-03-29 15:01:26 -07006256 sp<IOProfile> firstInexact;
6257 uint32_t updatedSamplingRate = 0;
6258 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6259 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006260 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006261 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006262 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006263 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006264 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006265 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006266 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006267 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006268 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006269 &channelMask /*updatedChannelMask*/,
6270 // FIXME ugly cast
6271 (audio_output_flags_t) flags,
6272 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006273 return profile;
6274 }
François Gaffie11d30102018-11-02 16:09:09 +01006275 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006276 samplingRate,
6277 &updatedSamplingRate,
6278 format,
6279 &updatedFormat,
6280 channelMask,
6281 &updatedChannelMask,
6282 // FIXME ugly cast
6283 (audio_output_flags_t) flags,
6284 false /*exactMatchRequiredForInputFlags*/)) {
6285 firstInexact = profile;
6286 }
6287
Eric Laurente552edb2014-03-10 17:42:56 -07006288 }
6289 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006290 if (firstInexact != nullptr) {
6291 samplingRate = updatedSamplingRate;
6292 format = updatedFormat;
6293 channelMask = updatedChannelMask;
6294 return firstInexact;
6295 }
Eric Laurente552edb2014-03-10 17:42:56 -07006296 return NULL;
6297}
6298
François Gaffieaaac0fd2018-11-22 17:56:39 +01006299float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6300 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006301 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006302 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006303{
jiabin9a3361e2019-10-01 09:38:30 -07006304 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006305
6306 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6307 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6308 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6309 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006310 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6311 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6312 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6313 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006314 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006315
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006316 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006317 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6318 mOutputs.isActive(ringVolumeSrc, 0)) {
6319 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006320 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006321 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006322 }
6323
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006324 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006325 if ((volumeSource != callVolumeSrc && (isInCall() ||
6326 mOutputs.isActiveLocally(callVolumeSrc))) &&
6327 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6328 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6329 volumeSource == alarmVolumeSrc ||
6330 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6331 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6332 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006333 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006334 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006335 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006336 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006337 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006338 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006339 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6340 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6341 // programmatically muted.
6342 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6343 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6344 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006345 bool exemptFromCapping =
6346 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6347 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006348 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6349 volumeSource, volumeDb);
6350 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006351 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6352 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6353 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006354 }
6355 }
Eric Laurente552edb2014-03-10 17:42:56 -07006356 // if a headset is connected, apply the following rules to ring tones and notifications
6357 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006358 // - always attenuate notifications volume by 6dB
6359 // - attenuate ring tones volume by 6dB unless music is not playing and
6360 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006361 // - if music is playing, always limit the volume to current music volume,
6362 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006363 if (!Intersection(deviceTypes,
6364 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6365 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006366 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6367 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006368 ((volumeSource == alarmVolumeSrc ||
6369 volumeSource == ringVolumeSrc) ||
6370 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6371 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6372 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6373 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6374 curves.canBeMuted()) {
6375
Eric Laurente552edb2014-03-10 17:42:56 -07006376 // when the phone is ringing we must consider that music could have been paused just before
6377 // by the music application and behave as if music was active if the last music track was
6378 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006379 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006380 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006381 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006382 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006383 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6384 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006385 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006386 float musicVolDb = computeVolume(musicCurves,
6387 musicVolumeSrc,
6388 musicCurves.getVolumeIndex(musicDevice),
6389 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006390 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6391 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6392 if (volumeDb > minVolDb) {
6393 volumeDb = minVolDb;
6394 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006395 }
jiabin9a3361e2019-10-01 09:38:30 -07006396 if (!Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6397 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006398 // on A2DP, also ensure notification volume is not too low compared to media when
6399 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006400 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006401 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006402 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6403 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006404 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6405 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006406 }
6407 }
jiabin9a3361e2019-10-01 09:38:30 -07006408 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006409 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006410 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006411 }
6412 }
6413
François Gaffie43c73442018-11-08 08:21:55 +01006414 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006415}
6416
Eric Laurent3839bc02018-07-10 18:33:34 -07006417int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006418 VolumeSource fromVolumeSource,
6419 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006420{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006421 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006422 return srcIndex;
6423 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006424 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6425 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006426 float minSrc = (float)srcCurves.getVolumeIndexMin();
6427 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6428 float minDst = (float)dstCurves.getVolumeIndexMin();
6429 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006430
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006431 // preserve mute request or correct range
6432 if (srcIndex < minSrc) {
6433 if (srcIndex == 0) {
6434 return 0;
6435 }
6436 srcIndex = minSrc;
6437 } else if (srcIndex > maxSrc) {
6438 srcIndex = maxSrc;
6439 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006440 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6441}
6442
François Gaffieaaac0fd2018-11-22 17:56:39 +01006443status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6444 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006445 int index,
6446 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006447 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006448 int delayMs,
6449 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006450{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006451 // do not change actual attributes volume if the attributes is muted
6452 if (outputDesc->isMuted(volumeSource)) {
6453 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6454 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006455 return NO_ERROR;
6456 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006457 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6458 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
6459 bool isVoiceVolSrc = callVolSrc == volumeSource;
6460 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
6461
Eric Laurent2517af32020-11-25 15:31:27 +01006462 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006463 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006464 // if sco and call follow same curves, bypass forceUseForComm
6465 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006466 ((isVoiceVolSrc && isScoRequested) ||
6467 (isBtScoVolSrc && !isScoRequested))) {
6468 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6469 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07006470 // Do not return an error here as AudioService will always set both voice call
6471 // and bluetooth SCO volumes due to stream aliasing.
6472 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006473 }
jiabin9a3361e2019-10-01 09:38:30 -07006474 if (deviceTypes.empty()) {
6475 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006476 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006477
jiabin9a3361e2019-10-01 09:38:30 -07006478 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6479 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07006480 // Force VoIP volume to max for bluetooth SCO device except if muted
6481 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07006482 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006483 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006484 }
jiabin9a3361e2019-10-01 09:38:30 -07006485 outputDesc->setVolume(
6486 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006487
François Gaffieaaac0fd2018-11-22 17:56:39 +01006488 if (isVoiceVolSrc || isBtScoVolSrc) {
Eric Laurente552edb2014-03-10 17:42:56 -07006489 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006490 // 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 +01006491 if (isVoiceVolSrc) {
6492 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006493 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006494 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006495 }
Eric Laurent18fba842016-03-31 14:41:26 -07006496 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006497 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6498 mLastVoiceVolume = voiceVolume;
6499 }
6500 }
Eric Laurente552edb2014-03-10 17:42:56 -07006501 return NO_ERROR;
6502}
6503
Eric Laurentc75307b2015-03-17 15:29:32 -07006504void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006505 const DeviceTypeSet& deviceTypes,
6506 int delayMs,
6507 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006508{
jiabincd510522020-01-22 09:40:55 -08006509 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006510 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6511 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6512 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07006513 curves.getVolumeIndex(deviceTypes),
6514 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006515 }
6516}
6517
François Gaffiec005e562018-11-06 15:04:49 +01006518void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6519 bool on,
6520 const sp<AudioOutputDescriptor>& outputDesc,
6521 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006522 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006523{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006524 std::vector<VolumeSource> sourcesToMute;
6525 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6526 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6527 toString(attributes).c_str(), on, outputDesc->getId());
6528 VolumeSource source = toVolumeSource(attributes);
6529 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
6530 sourcesToMute.push_back(source);
6531 }
Eric Laurente552edb2014-03-10 17:42:56 -07006532 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006533 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07006534 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006535 }
6536
Eric Laurente552edb2014-03-10 17:42:56 -07006537}
6538
François Gaffieaaac0fd2018-11-22 17:56:39 +01006539void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6540 bool on,
6541 const sp<AudioOutputDescriptor>& outputDesc,
6542 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006543 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006544{
jiabin9a3361e2019-10-01 09:38:30 -07006545 if (deviceTypes.empty()) {
6546 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006547 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006548 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006549 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006550 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006551 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006552 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6553 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6554 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07006555 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006556 }
6557 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006558 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6559 // ignored
6560 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006561 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006562 if (!outputDesc->isMuted(volumeSource)) {
6563 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006564 return;
6565 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006566 if (outputDesc->decMuteCount(volumeSource) == 0) {
6567 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07006568 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006569 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006570 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006571 delayMs);
6572 }
6573 }
6574}
6575
François Gaffie53615e22015-03-19 09:24:12 +01006576bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6577{
François Gaffiec005e562018-11-06 15:04:49 +01006578 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006579 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6580 return true;
6581 }
6582
6583 // has known usage?
6584 switch (paa->usage) {
6585 case AUDIO_USAGE_UNKNOWN:
6586 case AUDIO_USAGE_MEDIA:
6587 case AUDIO_USAGE_VOICE_COMMUNICATION:
6588 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6589 case AUDIO_USAGE_ALARM:
6590 case AUDIO_USAGE_NOTIFICATION:
6591 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6592 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6593 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6594 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6595 case AUDIO_USAGE_NOTIFICATION_EVENT:
6596 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6597 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6598 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6599 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006600 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006601 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006602 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006603 case AUDIO_USAGE_EMERGENCY:
6604 case AUDIO_USAGE_SAFETY:
6605 case AUDIO_USAGE_VEHICLE_STATUS:
6606 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006607 break;
6608 default:
6609 return false;
6610 }
6611 return true;
6612}
6613
François Gaffie2110e042015-03-24 08:41:51 +01006614audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6615{
6616 return mEngine->getForceUse(usage);
6617}
6618
6619bool AudioPolicyManager::isInCall()
6620{
6621 return isStateInCall(mEngine->getPhoneState());
6622}
6623
6624bool AudioPolicyManager::isStateInCall(int state)
6625{
6626 return is_state_in_call(state);
6627}
6628
Eric Laurent74b71512019-11-06 17:21:57 -08006629bool AudioPolicyManager::isCallAudioAccessible()
6630{
6631 audio_mode_t mode = mEngine->getPhoneState();
6632 return (mode == AUDIO_MODE_IN_CALL)
6633 || (mode == AUDIO_MODE_IN_COMMUNICATION)
6634 || (mode == AUDIO_MODE_CALL_SCREEN);
6635}
6636
Eric Laurentd60560a2015-04-10 11:31:20 -07006637void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6638{
6639 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006640 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006641 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006642 sourceDesc->sinkDevice()->equals(deviceDesc))
6643 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006644 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006645 }
6646 }
6647
6648 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6649 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6650 bool release = false;
6651 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6652 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6653 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6654 source->ext.device.type == deviceDesc->type()) {
6655 release = true;
6656 }
6657 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006658 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07006659 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6660 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6661 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006662 sink->ext.device.type == deviceDesc->type() &&
6663 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
6664 || strncmp(sink->ext.device.address, address,
6665 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006666 release = true;
6667 }
6668 }
6669 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006670 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6671 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006672 }
6673 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006674
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006675 mInputs.clearSessionRoutesForDevice(deviceDesc);
6676
Francois Gaffie716e1432019-01-14 16:58:59 +01006677 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006678}
6679
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006680void AudioPolicyManager::modifySurroundFormats(
6681 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006682 std::unordered_set<audio_format_t> enforcedSurround(
6683 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006684 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6685 for (const auto& pair : mConfig.getSurroundFormats()) {
6686 allSurround.insert(pair.first);
6687 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6688 }
Phil Burk09bc4612016-02-24 15:58:15 -08006689
6690 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6691 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07006692 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006693 // This is the resulting set of formats depending on the surround mode:
6694 // 'all surround' = allSurround
6695 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
6696 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
6697 // 'manual surround' = mManualSurroundFormats
6698 // AUTO: formats v 'enforced surround'
6699 // ALWAYS: formats v 'all surround' v 'enforced surround'
6700 // NEVER: formats ^ 'non-surround'
6701 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08006702
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006703 std::unordered_set<audio_format_t> formatSet;
6704 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
6705 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006706 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006707 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006708 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006709 formatSet.insert(*formatIter);
6710 }
6711 }
6712 } else {
6713 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6714 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006715 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006716
jiabin81772902018-04-02 17:52:27 -07006717 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006718 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006719 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6720 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6721 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08006722 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006723 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6724 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6725 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07006726 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006727 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08006728 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006729 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07006730 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006731 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006732}
6733
jiabin06e4bab2019-07-29 10:13:34 -07006734void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
6735 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07006736 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6737 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6738
6739 // If NEVER, then remove support for channelMasks > stereo.
6740 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07006741 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
6742 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006743 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006744 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07006745 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07006746 } else {
jiabin06e4bab2019-07-29 10:13:34 -07006747 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006748 }
6749 }
jiabin81772902018-04-02 17:52:27 -07006750 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6751 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6752 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006753 bool supports5dot1 = false;
6754 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006755 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006756 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6757 supports5dot1 = true;
6758 break;
6759 }
6760 }
6761 // If not then add 5.1 support.
6762 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07006763 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01006764 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006765 }
Phil Burk09bc4612016-02-24 15:58:15 -08006766 }
6767}
6768
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006769void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006770 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006771 AudioProfileVector &profiles)
6772{
6773 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006774 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006775
François Gaffie112b0af2015-11-19 16:13:25 +01006776 // Format MUST be checked first to update the list of AudioProfile
6777 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006778 reply = mpClientInterface->getParameters(
6779 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006780 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006781 AudioParameter repliedParameters(reply);
6782 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006783 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006784 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6785 return;
6786 }
Phil Burk09bc4612016-02-24 15:58:15 -08006787 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01006788 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006789 if (device == AUDIO_DEVICE_OUT_HDMI
6790 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006791 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006792 }
jiabin3e277cc2019-09-10 14:27:34 -07006793 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006794 }
François Gaffie112b0af2015-11-19 16:13:25 +01006795
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006796 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07006797 ChannelMaskSet channelMasks;
6798 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006799 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006800 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006801
6802 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006803 reply = mpClientInterface->getParameters(
6804 ioHandle,
6805 requestedParameters.toString() + ";" +
6806 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006807 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006808 AudioParameter repliedParameters(reply);
6809 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006810 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006811 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006812 }
6813 }
6814 if (profiles.hasDynamicChannelsFor(format)) {
6815 reply = mpClientInterface->getParameters(ioHandle,
6816 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006817 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006818 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006819 AudioParameter repliedParameters(reply);
6820 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006821 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006822 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006823 if (device == AUDIO_DEVICE_OUT_HDMI
6824 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006825 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006826 }
François Gaffie112b0af2015-11-19 16:13:25 +01006827 }
6828 }
jiabin3e277cc2019-09-10 14:27:34 -07006829 addDynamicAudioProfileAndSort(
6830 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006831 }
6832}
Eric Laurentd60560a2015-04-10 11:31:20 -07006833
Mikhail Naganovdc769682018-05-04 15:34:08 -07006834status_t AudioPolicyManager::installPatch(const char *caller,
6835 audio_patch_handle_t *patchHandle,
6836 AudioIODescriptorInterface *ioDescriptor,
6837 const struct audio_patch *patch,
6838 int delayMs)
6839{
6840 ssize_t index = mAudioPatches.indexOfKey(
6841 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6842 *patchHandle : ioDescriptor->getPatchHandle());
6843 sp<AudioPatch> patchDesc;
6844 status_t status = installPatch(
6845 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6846 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006847 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07006848 }
6849 return status;
6850}
6851
6852status_t AudioPolicyManager::installPatch(const char *caller,
6853 ssize_t index,
6854 audio_patch_handle_t *patchHandle,
6855 const struct audio_patch *patch,
6856 int delayMs,
6857 uid_t uid,
6858 sp<AudioPatch> *patchDescPtr)
6859{
6860 sp<AudioPatch> patchDesc;
6861 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6862 if (index >= 0) {
6863 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006864 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006865 }
6866
6867 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6868 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6869 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6870 if (status == NO_ERROR) {
6871 if (index < 0) {
6872 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01006873 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006874 } else {
6875 patchDesc->mPatch = *patch;
6876 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006877 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006878 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006879 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006880 }
6881 nextAudioPortGeneration();
6882 mpClientInterface->onAudioPatchListUpdate();
6883 }
6884 if (patchDescPtr) *patchDescPtr = patchDesc;
6885 return status;
6886}
6887
jiabinbce0c1d2020-10-05 11:20:18 -07006888bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
6889{
6890 const TrackClientVector activeClients = output->getActiveClients();
6891 if (activeClients.empty()) {
6892 return true;
6893 }
6894 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
6895 if (index < 0) {
6896 ALOGE("%s, no audio patch found while there are active clients on output %d",
6897 __func__, output->getId());
6898 return false;
6899 }
6900 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6901 DeviceVector routedDevices;
6902 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
6903 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
6904 patchDesc->mPatch.sinks[i].id);
6905 if (device == nullptr) {
6906 ALOGE("%s, no audio device found with id(%d)",
6907 __func__, patchDesc->mPatch.sinks[i].id);
6908 return false;
6909 }
6910 routedDevices.add(device);
6911 }
6912 for (const auto& client : activeClients) {
6913 // TODO: b/175343099 only travel the valid client
6914 sp<DeviceDescriptor> preferredDevice =
6915 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
6916 if (mEngine->getOutputDevicesForAttributes(
6917 client->attributes(), preferredDevice, false) == routedDevices) {
6918 return false;
6919 }
6920 }
6921 return true;
6922}
6923
6924sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
6925 const sp<IOProfile>& profile, const DeviceVector& devices)
6926{
6927 for (const auto& device : devices) {
6928 // TODO: This should be checking if the profile supports the device combo.
6929 if (!profile->supportsDevice(device)) {
6930 return nullptr;
6931 }
6932 }
6933 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
6934 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
6935 status_t status = desc->open(nullptr, devices,
6936 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
6937 if (status != NO_ERROR) {
6938 return nullptr;
6939 }
6940
6941 // Here is where the out_set_parameters() for card & device gets called
6942 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
6943 const audio_devices_t deviceType = device->type();
6944 const String8 &address = String8(device->address().c_str());
6945 if (!address.isEmpty()) {
6946 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
6947 mpClientInterface->setParameters(output, String8(param));
6948 free(param);
6949 }
6950 updateAudioProfiles(device, output, profile->getAudioProfiles());
6951 if (!profile->hasValidAudioProfile()) {
6952 ALOGW("%s() missing param", __func__);
6953 desc->close();
6954 return nullptr;
6955 } else if (profile->hasDynamicAudioProfile()) {
6956 desc->close();
6957 output = AUDIO_IO_HANDLE_NONE;
6958 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
6959 profile->pickAudioProfile(
6960 config.sample_rate, config.channel_mask, config.format);
6961 config.offload_info.sample_rate = config.sample_rate;
6962 config.offload_info.channel_mask = config.channel_mask;
6963 config.offload_info.format = config.format;
6964
6965 status = desc->open(&config, devices,
6966 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
6967 if (status != NO_ERROR) {
6968 return nullptr;
6969 }
6970 }
6971
6972 addOutput(output, desc);
6973 if (audio_is_remote_submix_device(deviceType) && address != "0") {
6974 sp<AudioPolicyMix> policyMix;
6975 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
6976 policyMix->setOutput(desc);
6977 desc->mPolicyMix = policyMix;
6978 } else {
6979 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
6980 address.string());
6981 }
6982
6983 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && hasPrimaryOutput()) {
6984 // no duplicated output for direct outputs and
6985 // outputs used by dynamic policy mixes
6986 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
6987
6988 //TODO: configure audio effect output stage here
6989
6990 // open a duplicating output thread for the new output and the primary output
6991 sp<SwAudioOutputDescriptor> dupOutputDesc =
6992 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
6993 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
6994 if (status == NO_ERROR) {
6995 // add duplicated output descriptor
6996 addOutput(duplicatedOutput, dupOutputDesc);
6997 } else {
6998 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
6999 mPrimaryOutput->mIoHandle, output);
7000 desc->close();
7001 removeOutput(output);
7002 nextAudioPortGeneration();
7003 return nullptr;
7004 }
7005 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007006 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7007 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7008 mPrimaryOutput = desc;
7009 }
jiabinbce0c1d2020-10-05 11:20:18 -07007010 return desc;
7011}
7012
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007013} // namespace android